6

I want to add the <br/> (newline) to text box when user clicks on the enter button.

How can I achieve it in jquery onkeyup event. Can one show me the example or any good website implementing it.

Thank you

S L
  • 14,262
  • 17
  • 77
  • 116
sharath
  • 176
  • 1
  • 10
  • Might this be something: http://stackoverflow.com/questions/2157739/jquery-how-can-i-add-line-break-to-form-input/2157769#2157769 ? – johnny Mar 28 '11 at 05:46

2 Answers2

7

Copied from here Caret position in textarea, in characters from the start 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 guess all text-editors (WYSIWYG) do it all the time.

Community
  • 1
  • 1
S L
  • 14,262
  • 17
  • 77
  • 116
  • thanks for your answer but i dont want to display
    when user press enter how can i add it into the hidden field .i am new to the jquery can u help me
    – sharath Mar 28 '11 at 07:07
  • @sarath, well, i think these text editors use `hidden` element to store the values. These guys are pretty smart. – S L Mar 28 '11 at 07:10
  • i dont want to use any text editors now since i am using this text box only in 2 places and i dont have time to explore it, so can i make changes here only so that i can finish it early – sharath Mar 28 '11 at 07:19
  • @sarath well, you can store this value in a hidden element - there's no other way (and also put some (single) character) so that backspace allows deleting it. – S L Mar 28 '11 at 07:21
1

Something along the lines of :

$('#some-field').keyup(function(e){
  if (e.keyCode == '13') {
     e.preventDefault();
     $(this).append("<br />\n");
  }
});
OneOfOne
  • 95,033
  • 20
  • 184
  • 185