Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding <br/> to the text-box when user press enter key in jquery

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

like image 681
sharath Avatar asked Mar 28 '11 05:03

sharath


2 Answers

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.

like image 156
Santosh Linkha Avatar answered Nov 12 '22 09:11

Santosh Linkha


Something along the lines of :

$('#some-field').keyup(function(e){
  if (e.keyCode == '13') {
     e.preventDefault();
     $(this).append("<br />\n");
  }
});
like image 22
OneOfOne Avatar answered Nov 12 '22 08:11

OneOfOne