I\'m using the following HTML code to autoselect some text in a form field when a user clicks on the field:
This question was posted five years ago, but with HTML5, you can make this feature with the placeholder attribute.
<input type="text" name="fname" placeholder="First name">
If you really insist on sticking with onfocus, then you'll need to add onmouseup="return false"
too.
Thanks ilawton. This works for me
<input type="text" onfocus="this.searchfocus = true;" onmouseup="if(this.searchfocus) {this.select(); this.searchfocus = false;}" />
The way I got around this was by creating a wrapper function that uses setTimeout()
to delay the actual call to select()
. Then I just call that function in the focus event of the textbox. Using setTimeout defers the execution until the call stack is empty again, which would be when the browser has finished processing all the events that happened when you clicked (mousedown, mouseup, click, focus, etc). It's a bit of a hack, but it works.
function selectTextboxContent(textbox)
{
setTimeout(function() { textbox.select(); }, 10);
}
Then you can do something like this to do the selection on focus:
<input onfocus="selectTextboxContent(this);" type="text" value="Search">