Required <select>

It seems that in the current Web Forms 2 spec, there is no way to natively specify some options as invalid selections. Now, the idea of this is correct since a select by definition is a list of predefined valid values, but there is a use case for which an option is invalid.

Say you want to let the user select a value, but it is important that the default value is not mindlessly selected. You'd want to add an option labelled "Select one:" as the first and default value, but there's no way to invalidate that control dynamically as you can with other input elements. Instead, the form gets submitted to and rejected from the server, in contrast with the point of client-side validation.

A solution

Because of this, I wrote a script that will invalidate any select option with an empty value. Note that currently, only Opera 9 supports Web Forms 2, but Firefox has stated they will implement it in the near future - and they support every bit of code used in this snippet, so it will work in Firefox as soon as WF2 is implemented.

 0 ? 'h:' : '';
    var res = document.evaluate('//'+ns+'select',document,
        function(p){return 'http://www.w3.org/1999/xhtml';},
        4,null);
    var elem=null;
    while(elem = res.iterateNext()){
        if(!elem)break;
        invalid_select_check({'target':elem}); // do initial check
        elem.addEventListener('change',invalid_select_check,false);
    }
}
window.addEventListener('load',invalid_select_init(),false);
]]>

Test it yourself

The following form should only submit if both selectboxes has selected a non-default value in a browser that has Web Forms 2 implemented (Opera).

Get the code

Download invalid_select.js.

Contact me