开发者

JavaScript textbox new line replacement

开发者 https://www.devze.com 2023-01-04 20:11 出处:网络
I have a text box that can allow the users to hit enter. When they hit enter I check the input and replace the carriage return with \\n. However it still sends to my database a carriage return.

I have a text box that can allow the users to hit enter. When they hit enter I check the input and replace the carriage return with \n. However it still sends to my database a carriage return. What could be wrong?

Here is the 开发者_C百科code:

var pp = comment.value;  
alert(pp.replace(/\r?\n|\r/g, "\n"));  
comment.value =  pp.replace(/\r?\n|\r/g, "\n");  

and in my database I still get carriage return character even though I am replacing it.


If you set an onsubmit handler on your form, you'll be able to change the contents of the textarea element before sending it. You can then use the replace method to change every \r to \n:

<!DOCTYPE html>
<html>
 <head>
  <meta charset=utf-8>
  <title>Replace carriage returns in textarea</title>
 </head>
 <body>
  <form id="theForm">
   <textarea id="theTextarea" name="txtarea" rows=10 cols=50></textarea>
   <input type="submit" value="Send">
  </form>
  <script>
   function replace_newlines() {
     var textField = document.getElementById("theTextarea");
     var textString = textField.value;
     textField.value = textString.replace(/\r/g, "\n");
   }

   document.getElementById("theForm").onsubmit = replace_newlines;
  </script>
 </body>
</html>


Here is an example that does it in pure javascript, but it'd be much cleaner if you were using something like jquery.

<html>
<head>
</head>
<body>
<textarea id='txt'></textarea>
<script type='text/javascript'>
    var txtarea = document.getElementById('txt');
    txtarea.onkeypress = keyHandler;
    function keyHandler(e){
        if (document.all) { e = window.event; }
        if (document.layers || e.which) { pressedKey = e.which; }
        if (document.all) { pressedKey = e.keyCode; }
        if(pressedKey == '13'){
            txtarea.value = this.value + '\\n';
            return false;
        }

    }
</script>
</body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消