Jquery input select all on focus

inputjquery

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.

Best Answer

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