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. )}; }); 
3
  • 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. Commented May 10, 2011 at 16:25
  • i found this - stackoverflow.com/questions/511088/… - but not sure it helps ? Commented May 10, 2011 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? Commented May 10, 2011 at 16:27

1 Answer 1

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(); } }); 
Sign up to request clarification or add additional context in comments.

1 Comment

hey dave - great thanks this works :) I think just the preventDefault(); is ok for me but +1 for adding the second as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.