Reputation: 32061
I have a form like so:
<form action='word.php' name = 'searchbox'>
<input type='text' name='word' id = 'searchbox' value = 'default'>
</form>
In my body I have:
<body onLoad="searchbox.word.focus()">
You can see the fiddle here: http://jsfiddle.net/WEZ7S/
What I'm trying to achieve is just have a blinking cursor at the end of "default", but instead the whole word gets selected instead.
Surprisingly Google hasn't been able to find any solutions. How would I do this?
Upvotes: 0
Views: 2997
Reputation: 96790
Use setSelectionRange
(Chrm, FF):
var len = searchbox.word.length;
searchbox.word.focus();
searchbox.word.setSelectionRange(len, len);
Upvotes: 0
Reputation: 298046
You can get around this by resetting the .value
property of the element:
searchbox.word.focus();
searchbox.word.value = searchbox.word.value;
There are also less hacky solutions: Use JavaScript to place cursor at end of text in text input element
Demo: http://jsfiddle.net/WEZ7S/1/
Upvotes: 3
Reputation: 16961
From a previously answered question: https://stackoverflow.com/a/13371452/1238887
Here's a nifty little trick:
$(document).ready(function() {
var $field = $("#searchbox"),
oldVal = $field.val();
$field.focus().val('').val(oldVal);
});
DEMO: http://jsfiddle.net/X7Y8S/
Upvotes: 1