Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 486
user2571510 Avatar asked Mar 23 '14 14:03

user2571510


2 Answers

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).

like image 168
benomatis Avatar answered Oct 01 '22 15:10

benomatis


you will need to find the caret position first as follow:

    var caretPos = function() {
        var el = $("#details").get(0);
        var pos = 0;
        if('selectionStart' in el) {
            pos = el.selectionStart;
        } else if('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }

taken from :here

then you do:

var textofDetails = $("#details").val();
jQuery("#detail").val(textofDetails.substring(0, caretPos) + "<br/>" + textofDetails.substring(caretPos) );

Major EDIT:

no need for all the above ; your function will be

function replaceNewLine(){

    jQuery("#detail").val().replace(/\\n/g, "<br />");
}

source: so - here

like image 27
stackunderflow Avatar answered Oct 01 '22 14:10

stackunderflow