Search code examples
javascriptjqueryhtmltextareacursor-position

jQuery: add line break at cursor position when hitting Enter


I have a form with a textarea (id = details).

Is there a way I can insert the HTML code for a line break (<br />) at the cursor position when hitting Enter within this textarea ?

I would only need this to get to work in IE.

<textarea class="input height120 elastic span12" name="details" id="details" onkeyup="countCharLimit(event)" onpaste="countCharLimit(event)"></textarea>

Solution

  • Try this:

    $('textarea').keypress(function (e){
        if(e.keyCode == 13){
            $('textarea').val($('textarea').val()+"<br />");
        }
    });
    

    You could try and fiddle with it here

    EDIT: I realized this is adding a <br /> at the end only, after some more research, I found this solution:

    $('textarea').keypress(function (e){
        if(e.keyCode == 13){
            e.preventDefault();
            this.value = this.value.substring(0, this.selectionStart)+"<br />"+"\n";
        }
    });
    

    Here is a fiddle for this one

    Source (mostly): Insert text into textarea with jQuery

    EDIT AGAIN: Looks like the OP wanted the text at the end to also be cleared, so I updated my code accordingly (for other's seeing this: check out the first edit of my relevant fiddle for the case you'd want to keep the remaining text).