One nice form trick

One of the most useful thing on forms is an “autoselect” function. How is this work? Let’s assume that you have a standard search box:

When textbox is focused you can do three things:

  1. Do nothing. Let the user to delete all text. Not good for lazy people, right? :D
  2. Autoclear box. But if user want only to change a letter (typo) or add another word, then he should re-type all things. Not good for usability.
  3. Autoselect box content. Is just like the user double clicks on the text. How can you do this? Read further to see :)
var initValue;
$(document).ready(function(){
$(':text').each(function(){
	$(this).focus(function(){
		initValue = $(this).attr('value');
		$(this).select();
	});
	$(this).blur(function(){
		if($(this).val() == ''){
			$(this).val(initValue);
		}
	});
});
});

What is the best thing with this? Well… If an user just leave the text box blank, that form is auto filled with previous value.

Pretty nice, huh? Well… I think is pretty useful too :)

No related posts.

3 thoughts on “One nice form trick

  1. I prefer your second option, only making sure you’re not clearing the input value unless it’s the default (specified in the HTML), so that if the user types in something and then returns to type in some more you don’t ruin their precious work :)

    (the default value of a text input is stored in its defaultValue property)

Leave a Reply