Questions or Comments? Drop me a line.
Checkboxes that act like radio buttons.
So the idea is you want to be able to submit from a selection of options the general type being something like this:
In this case you want the set of checkboxes to act as if they were a radio button in respect to the other radio buttons. So if you select one of the checkboxes any radio buttons that have been selected are unselected. And if you select a radio button it will unselect any selected checkboxes. Of course your standard form (like the one above doesn't do this.
What you want is something like the form below. Nice isn't it? How do we do this? By the power of JavaScript, so of course your server side code needs to be able to handle people not having scripting turned on but such is life. Anyway once you've got bored with the form onto the explanation.
Ok. Here is the code.
function crossInputChange()
{
if ( this.checked == false ) { return true }
var list = document.getElementsByName( this.name );
for ( var x = 0; x < list.length; x++ )
{
if( list[x].type && this.type
&& ( this.type != list[x].type )
&& ( this.form == list[x].form ) )
{
list[x].checked = false;
}
}
return true;
}
function setupCrossInput(name)
{
return function()
{
var list = document.getElementsByName( name );
for ( var x = 0; x < list.length; x++ )
{
addEvent( list[x], 'click', crossInputChange );
}
}
}
Note that this code uses Scott Andrew's addEvent method, or any function with the same name and calling convention like the ones entered for the Add Event recoding contest.
If you just want to use this in your pages just cut and paste the code into your page and attach one or more onload events.
Each one calls setupCrossInput with the input name you want this effect applied to, so if you wanted to set this effect on
all inputs with a name of 'colours' you would add addEvent( window, 'load', setupCrossInput('colours') ). This
would set everthing up. Ta Da! Of course if you want a quick run through of what it's doing then either mouse over the relevant underlined bits or
see below.
It's not really that hard, the main trick is understanding anonymous functions (or lambda functions as they can be called). The script uses them so
you can reuse the the setup and change functions for different sets of inputs on the same page or reuse the code across different pages which
is always nice. The setupCrossInput function creates a fucntion that is to be called once the
DOM has been loaded that zips through all the objects with the given name and applies
crossInputChange as the click event.
crossInputChange firstly makes sure you have set the input to true. Then loops through all the elements with the same name.
It sets them to unchecked if they don't have the same type as this and they are in the same form. The demonstration form below shows how
you can apply the effect to multiple input names and notice how modifying the colour vlaues here dosen't change the settings in the form above.