Question

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>
Était-ce utile?

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

Autres conseils

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

Yes, sure. It seems to be so, that you need keydown event processing and, possible, setTimeout 0 hack, look here: Why is setTimeout(fn, 0) sometimes useful?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top