0

Here is example http://jsfiddle.net/omuL8doa/3/

If I press Enter, jquery inserts <br/> in current place. This is ok.

But after Enter I (cursor) goes to the end of the text. But I need that cursor remains in 'curent' place (the same behavior if I pres enter in Word or Notepad. I mean, press Enter, goes one line below and remains there.

What need to modify to the code?

Here is the code

$('textarea').keydown(function(ev){
if(ev.keyCode == 13){
var caretPos = document.getElementById("main_text").selectionStart;
var textAreaTxt = jQuery("#main_text").val();
var txtToAdd = "<br/>";
jQuery("#main_text").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
}
});
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Andris
  • 1,434
  • 1
  • 19
  • 34

2 Answers2

1

DEMO

$('textarea').keydown(function(ev){        
    if(ev.keyCode == 13){
        ev.preventDefault(); //added
        var caretPos = this.selectionStart;
        var textAreaTxt = this.value;
        var txtToAdd = "\n"; //changed
        $(this).val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
        var sePos = caretPos + txtToAdd.length //add
        this.setSelectionRange(sePos,sePos); //added
    }
});
PeterKA
  • 24,158
  • 5
  • 26
  • 48
0

This may help

<script type='text/javascript'> 
    $(window).load(function(){
        $('textarea').keydown(function(ev){
            if(ev.keyCode == 13){

                obj = document.getElementById("main_text");
                $this = $(obj);
                txtToAdd = "<br/>";
                textAreaTxt = jQuery(obj).val();
                pos_start = obj.selectionStart;
                pos_end = obj.selectionEnd;

                val = (textAreaTxt.substring(0, pos_start) + txtToAdd + textAreaTxt.substring(pos_end));

                $("#main_text").val(val);

                obj.selectionStart = obj.selectionEnd = (pos_start + txtToAdd.length);

                ev.preventDefault();

            }
        });
    });
</script>

This is a simple idea, and there are lots of other codes here on stackoverflow.

Soley
  • 1,716
  • 1
  • 19
  • 33