I'm using this code to try and select all of the text in the field when a user focuses on the field. What happens is, it selects all for a second, then its unselected and the typing cursor is left where I clicked...
$("input[type=text]").focus(function() { $(this).select(); });
I want it all to remain selected.
select to select all the text in the input as the value of the onFocus prop. e. target is the input element so we can call select on it to select all the text.
Using jQuery With jQuery, you can use the . focus() method to trigger the “focus” JavaScript event on an element. This method is a shortcut for . trigger("focus") method.
The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.
Try using click
instead of focus
. It seems to work for both mouse and key events (at least on Chrome/Mac):
jQuery < version 1.7:
$("input[type='text']").click(function () { $(this).select(); });
jQuery version 1.7+:
$("input[type='text']").on("click", function () { $(this).select(); });
Here is a demo
I think that what happens is this:
focus() UI tasks related to pre-focus callbacks select() UI tasks related to focus (which unselect again)
A workaround may be calling the select() asynchronously, so that it runs completely after focus():
$("input[type=text]").focus(function() { var save_this = $(this); window.setTimeout (function(){ save_this.select(); },100); });
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