Auto-select input field with jQuery, without having a deselect on clicking

July 26th, 2011 by Alex Leave a reply »

Recently, i had a bug which was kinda confusing.. The input field was easily selected using the standard input select() method, so i could do like this:

$('input').focus(function() { $(this).select(); }).click(function() { $(this).select(); });

Easy as pie, it was auto-selected on mouse click AND when tab-clicking between fields. But, if it was already selected after focus, and then i clicked again, it was deselected.. which i didn’t need to. So the workaround was to cancel the standard mouseup event:

$('input').focus(function() { $(this).select(); }).click(function() { $(this).select(); }).mouseup(function(e) { e.preventDefault(); });

And that’s it! Now it’s always auto-selected and deselected only on focus change.


Comments are closed.