Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move the cursor to the front of a textbox which has text in it?

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/

like image 931
Nick Brunt Avatar asked Jul 13 '11 17:07

Nick Brunt


People also ask

How do you get the cursor position in a TextBox in HTML?

Syntax: // will give the current position of the cursor document. getElementById("id"). selectionStart; // will get the value of the text area let x= $('#text1').

How do I change cursor position?

SetCursorPosition(Int32, Int32) Method is used to set the position of cursor. Basically, it specifies where the next write operation will begin in the console window.

How do I move the input field cursor?

To move the cursor to the beginning of an input field:Use the setSelectionRange() method to move the cursor to the beginning of the input field. Call the focus() method on the input element. The focus method will move the cursor to the beginning of the element's value.


1 Answers

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 });
like image 78
pimvdb Avatar answered Nov 15 '22 01:11

pimvdb