8

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.  
        )};    
});
Tom
  • 83
  • 1
  • 4
  • Do you have a link or some samples we can look at? My first guess would be some way of preventing default, but I can't be sure. – sdleihssirhc May 10 '11 at 16:25
  • i found this - http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text-in-text-input-element - but not sure it helps ? – Tom May 10 '11 at 16:26
  • I meant something that *you've* done. Your question makes it sounds like you've written some actual code. Can we see *that*? – sdleihssirhc May 10 '11 at 16:27

1 Answers1

6

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();
    }
});
David Fullerton
  • 3,224
  • 27
  • 38
  • hey dave - great thanks this works :) I think just the preventDefault(); is ok for me but +1 for adding the second as well. – Tom May 10 '11 at 16:36