to the text box when the user presses the enter key in jquery I want to add the text
(new line) to the text box when the use...">

By adding <br/"> to the text box when the user presses the enter key in jquery

I want to add the text <br/> (new line) to the text box when the user presses the enter button.

How can I achieve this in a jquery onkeyup event. Can you show me an example or any good website that implements it.

thanks

+6
jquery newline onkeyup
source share
2 answers

Copied here. Caret position in text field, in characters from the beginning . See DEMO .

 <script src="jquery.js"></script> <script> $(function () { $('#txt').keyup(function (e){ if(e.keyCode == 13){ var curr = getCaret(this); var val = $(this).val(); var end = val.length; $(this).val( val.substr(0, curr) + '<br>' + val.substr(curr, end)); } }) }); function getCaret(el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; } </script> <div id="content"> <textarea id="txt" cols="50" rows="10"></textarea> </div> 

Well, I think all text editors (WYSIWYG) do this all the time.

+7
source share

Something along the lines of:

 $('#some-field').keyup(function(e){ if (e.keyCode == '13') { e.preventDefault(); $(this).append("<br />\n"); } }); 
+1
source share

All Articles