April 16th, 2008 at 11:20 am

Clear a sized select field

If you have have a select form element with a size attribute, one common option for the user is to leave it empty (especially in combination with multiple). The problem is, as soon as one or more options are selected, it is quite impossible in most browsers, to not select anything at all. And even if there is a way, it is not easy to accomplish. Try for yourself to deselect all items:

With a little JavaScript magic, we can offer a button to clear the select field:

JavaScript:
  1. function nl_clear_select(element)
  2. {
  3.     var opt_length = document.getElementById(element).options.length;
  4.     for (var i = 0; i <opt_length; i++)
  5.         document.getElementById(element).options[i].selected = false;
  6. }

Now try again to clear the select field. Hint: clicking on "Clear selection" will help a lot. ;)

Clear selection

Neat, eh?