W3C home > Mailing lists > Public > whatwg@whatwg.org > October 2006

[whatwg] [WF2] <select required>

From: Robert <mail@robbiegee.com>
Date: Wed, 04 Oct 2006 01:35:27 +0200
Message-ID: <op.tgvc5dzcir1lcs@daemontooth.bredbandsbolaget.se>
On Mon, 02 Oct 2006 16:35:32 +0200, Simon Pieters <zcorpan at hotmail.com>  
wrote:

> I've seen a case where a <select> is used and the user is required to  
> change its value, as in:
>
>    <select name="test" required>
>     <option value="">Select one:
>     <option>Foo
>     <option>Bar
>    </select>
>
> Now this can be done with radio buttons instead, but why can't the above  
> be supported? That is, make required apply to <select>s and if the value  
> is empty then required is not satisfied. (Same for <select multiple>.)


Submitting an empty value may be wanted, and since a select by definition  
is a list of predefined valid values, it would make little sense to  
prevent the user from selecting some of them. However, I agree with the  
use case of the invalid starter value so users must consciously select a  
value they wanted instead of the default one.

The following script will do exactly what you wanted, although Opera  
doesn't seem to use the custom error message for some reason. I'm not sure  
if that's my fault or Opera's due to my lack of experience with WF2, but  
it does prevent form submissions just fine as long as there are invalid  
selects.

The script works in Opera 9.02.

<script type="text/javascript"><![CDATA[
function checkSelect(e){
    var test = e.target;
    if(e.target.value == '')
       e.target.setCustomValidity('You must select a value.');
    else
       e.target.setCustomValidity(null);
}

// Use '//select' for html documents, or use a wrapper function
// that strips namespace prefixes for plain 'ol html.
var res = document.evaluate('//html:select',document,
    function(pfx){return 'http://www.w3.org/1999/xhtml';},4,null);
var elem=null;
while(elem = res.iterateNext()){
    if(!elem)break;
    checkSelect({'target':elem}); // do initial check
    elem.addEventListener('change',checkSelect,false);
}
]]></script>


--
Robert Gr?sdal
Received on Tuesday, 3 October 2006 16:35:27 UTC

This archive was generated by hypermail 2.4.0 : Wednesday, 22 January 2020 16:58:48 UTC