5

I have this text box:

<input type="text" name="url" id="url-input" />

and this code:

var inputText = "Hello World";
$(document).ready(function() {
  $("#url-input").focus();
  $("#url-input").val(inputText);
});

As it is, the cursor is displayed at the end of the textbox after the words "Hello World" (no matter in which order I add focus or change the value). How can I move it to the front?

Thanks

EDIT - Here's the jsFiddle: http://jsfiddle.net/dmRND/

Nick Brunt
  • 9,533
  • 10
  • 54
  • 83

2 Answers2

7

In decent web browsers, you have access to the selectionStart and selectionEnd properties which represent the selection. When they are both 0, it comes down to no selection and the caret at the beginning:

$("#url-input").prop('selectionStart', 0)
               .prop('selectionEnd', 0);

http://jsfiddle.net/efek3/

Another thing of jQuery is chaining: $(...).func1().func2(), so you need the selector once only.

Yet another thing of jQuery is that most functions support objects as parameter so you could also do:

$("#url-input").prop({ selectionStart: 0,
                       selectionEnd:   0 });
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • @Nick Brunt: That remembers me of this answer: http://stackoverflow.com/questions/263743/how-to-get-cursor-position-in-textarea/3373056#3373056. – pimvdb Jul 13 '11 at 17:40
0

I use this small jquery plug in: https://gist.github.com/DrPheltRight/1007907

ninetiger
  • 1,106
  • 11
  • 12