简体   繁体   中英

Want to capture 'Enter' key press in HTML form field

I have a HTML form text field( this is a form field),where I want to capture the whole text the end user put into that field along with the Enter key pressed for new lines.Like if i give an example, lets assume, I am putting the below string into the form text field exactly as it looks here:

I 
Pressed
Enter for a new Line.

Now, I want to save this filed input into the database exactly as end user filled it,for that My database string may looks like this

"I</br>Pressed</br>Enter for a new Line."

That is okey with me.But i don't want to store it like "I Pressed Enter for a new Line."

I have done it anyway.But there are many issues in my coding. Also, my requirement is it should be implemented in such a way, show that the same logic could be applied when the form will be open for editing and there will already be value in that text field from Database.

Can anybody please help me?

you can use the replace() method for that,

$("textarea").val().replace(/\n/g, "<br />")

Edit

function captureEnter() {
 if (window.event.keyCode == 13) {
    document.getElementById("txtArea").value =document.getElementById("txtArea").value + "<br/>";
    return false;
}
else {
    return true;
}
}

HTML

<textarea id="txtArea" onkeypress="captureEnter();"></textarea>

If I understand you correctly, you want to capture when someone presses enter in a an input of type=text , and replace it with <br/> . If so, use the onkepress event, and listen for charcode 13, then add the "
" manually.

var tf = document.getElementById('myTextFIeld'); 
//or whatever method to find it you prefer.
tf.onkeypress = function(e) { 
  //or addEventListener('keypress',...) if you'd rather
  if (e.charCode === 13) {
    this.value += '<br/>'
  }
}

You could also do it server side with PHP and nl2br() :

$thetext = nl2br($_GET['textarea']);

http://php.net/manual/en/function.nl2br.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM