views:

50

answers:

2

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 db a carriage return. What could be wrong?

Here is the 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 db I still get carriage return character even though I am replacing it.

+1  A: 

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>
wowo_999
You're testing for `document.all` and conclude that it's IE you're dealing with? That's the wrong way of browser detection. You'd rather use [feature detection](http://www.nczonline.net/blog/2009/12/29/feature-detection-is-not-browser-detection/). Also, use `var` to declare your variables locally, as you'll overwrite an earlier declared `e` now: `var e = e || window.event;`, etc.
Marcel Korpel
Since e is a parameter to the function, it's already "declared", and considered to be within the local scope of the function.
Ryan Kinal
@Ryan: Correct, `e` is, but `pressedKey` isn't.
Marcel Korpel
Indeed... missed that one :-)
Ryan Kinal
+1  A: 

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>
Marcel Korpel