Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Textbox Cursor to end of Text?

I am trying to use jQuery to basically replace the cursor at the end of the text in a textbox AFTER the user hits "enter"

I have the "enter" part working - but I've no idea how [after the enter part] - I can get the cursor to return to the end of the inputted text inside the textbox ?

i.e. at the moment, when the user hits enter - the cursor goes to a new line and I want it to basically go to the end of the current text?

Some code:

jQuery('#textbox').keyup(function (e) {
        if (e.keyCode == 13) {
            ... submits textbox
        }
        jQuery(this).focus(function() {
          var val = this.input.value; //store the value of the element
          this.input.value = ''; //clear the value of the element
          this.input.value = val; //set that value back.  
        )};    
});
like image 620
Tom Avatar asked May 10 '11 16:05

Tom


1 Answers

If you just want to prevent the 'enter' key from creating a newline, you can use preventDefault to block it.

$("textarea").keypress(function (event) {
    if (event.which == '13') {
        event.preventDefault();
    }
});

fiddle

If you really want enter pressed anywhere in the input to go to the end of the input, you can also reset the value which will always put the cursor at the end of the input:

$("textarea").keypress(function (event) {
    if (event.which == '13') {
        var val = $(this).val();       
        $(this).val('');
        $(this).val(val);
        event.preventDefault();
    }
});
like image 200
David Fullerton Avatar answered Nov 09 '22 01:11

David Fullerton