[Javascript] Javascript - radio buttons error

Andrew Clover and-babble at doxdesk.com
Sat Mar 26 22:15:34 CST 2005

 > but for some reason it does not work if there is only 1 radio
 > button on the form...can anyone tell me why?

Because the JS (DOM Level 0) Form interface is badly designed.

   var f= document.getElementById('someform');
   var el= f.elements.elname;

If there is one field with name="elname", el will be an 
HTMLInputElement. If there is more than one, el will be an Array of 
HTMLInputElements. As Netscape's original JavaScript spec helpfully states:

   You need to be aware of this situation in your code and know whether
   myField refers to a single element or to an array of elements.

One way of guessing which is the case is to check for the existence of a 
'length' attribute and assume that we have a single input if it's 
undefined. This works as long as no-one starts adding 'length' 
properties to form field objects. For example:

   // Get list of field elements by name - always return Array/NodeList
   function getFieldsByName(form, name) {
     var el= form.elements[name];
     if (!el) return new Array();
     if (!el.length) return new Array(el);
     return el;

Andrew Clover
mailto:and at doxdesk.com

More information about the Javascript mailing list