JQuery: add line break at cursor position when pressing Enter

I have a form with a text box ( id = details).

Is there a way to insert HTML code for line break ( <br />) at cursor position when I press Enter in this text box?

I only needed this to work in IE.

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

Thanks so much for any help with this, Tim.

+4
source share
3 answers

Try the following:

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

You can try and script here

EDIT: I realized that this addition was <br />only at the end, after several studies, I found this solution:

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

( ): jQuery

: , OP , , ( , : , ).

+4

, :

    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;
    }

:

:

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

:

;

function replaceNewLine(){

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

: -

+2

Oh sure. It looks like you need keydown event handling and maybe setTimeout 0, look here: Why is setTimeout (fn, 0) sometimes useful?

0
source

Source: https://habr.com/ru/post/1533058/


All Articles