I'm trying to set the cursor in a text field with a focus function. I've made some research but none of the provided solutions seemed to work in Google Chrome. In Internet Explorer and Firefox this solution is working fine:
The js:
$('#Search').focus(function() { var SearchInput = $('#Search'); var strLength= SearchInput.val().length; SearchInput.focus(); SearchInput[0].setSelectionRange(strLength, strLength); });
The HTML:
<input type="text" id="Search" value="Hello World" />
Here's the link to my jsfiddle.
Is there any way to make this work in Google Chrome too?
We can place the cursor at the end of the text in a text input element by using different JavaScript functions. HTMLInputElement.setSelectionRange (): The HTMLInputElement.setSelectionRange () is a method that sets the start and end positions of the current text selection in an <input> or <textarea> element.
Call the focus () method on the input element. The focus method will move the cursor to the end of the input element's value. Here is the HTML for the examples in this article. Copied! And here is the related JavaScript code. Copied! We used the setSelectionRange to set the start and end positions of the current text selection in the input element.
Turn on Navigate pages with a text cursor. Tip: You can also turn on caret browsing with the keyboard shortcut F7 . On Chromebook, the keyboard shortcut is Ctrl + Search + 7, or Ctrl + Launcher + 7. Was this helpful? How can we improve it?
In order to set caret cursor position in content editable elements like div tag is carried over by JavaScript Range interface. The range is created using document.createRange () method. First, create Range and set position using above syntax. On button click assign input value to range function to return cursor position on div.
It seems like the focus event is fired before the cursor is placed when you focus an input, a hacky workaround would be to use a setTimeout like so:
$('#Search').focus(function() { setTimeout((function(el) { var strLength = el.value.length; return function() { if(el.setSelectionRange !== undefined) { el.setSelectionRange(strLength, strLength); } else { $(el).val(el.value); } }}(this)), 0); });
Try this fiddle: http://jsfiddle.net/esnvh/26/
Edited to 0ms timeout, as @SparK pointed out this is enough to push to end of execution queue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With