Page 1 of 1
Checking groups of radio buttons
Posted: Thu Feb 10, 2011 11:34 am
by social_experiment
This is basically a form validation related question, how do you go about check that a radio button (or a checkbox) has been set.
Sample code
Code: Select all
<label for="need_bond">Need a bond?</label>
Yes<input type="radio" name="need_bond" id="need_bond" value="Y" />
No<input type="radio" name="need_bond" id="need_bond" value="N" />
I've tried the code below but it doesn't work. My goal is to check that a user submits at least 1 option of the two.
Code: Select all
function checkBoxes()
{
var need_bond = window.document.offerForm.need_bond;
if (need_bond.checked == false)
{
alert('Check a box please');
return false;
}
return true;
}
Re: Checking groups of radio buttons
Posted: Thu Feb 10, 2011 3:17 pm
by tr0gd0rr
Since you have more than one radio button, `document.offerForm.need_bond` will actually be a collection you can iterate like an array:
Code: Select all
var radios = document.offerForm.need_bond;
var hasChecked = false;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
hasChecked = true;
break;
}
}
if (!hasChecked) {
//...
}
Re: Checking groups of radio buttons
Posted: Fri Feb 11, 2011 1:12 am
by social_experiment
Thanks for the reply. This works great so i need to move onto the next logical step, how do i check multiple sets on the same form? Below is my code, I tried doing this with just 2 group but the form is submitted regardless of the state of the 2 group of radio elements.
Code: Select all
for (i = 0; i < need_bond.length; i++)
{
if (need_bond[i].checked)
{
hasChecked = true;
break;
}
}
if (hasChecked == false)
{
alert('Need bond hasn\'t been checked 1');
return false;
}
else {
for (i = 0; i < need_a_bond.length; i++)
{
if (need_a_bond[i].checked)
{
hasChecked = true;
break;
}
}
if (hasChecked == false)
{
alert('Need a bond hasn\'t been checked 2');
return false;
}
}
return true;
Re: Checking groups of radio buttons
Posted: Fri Feb 11, 2011 1:29 pm
by tr0gd0rr
The new javascript looks good. Are you properly attaching that like `<form onsubmit="return checkRadios()"...>` or the like?
You can try putting some `console.log()` statements in to see what is going on.
Re: Checking groups of radio buttons
Posted: Fri Feb 11, 2011 4:21 pm
by social_experiment
The 'array' thing gave me an idea
Code: Select all
function checkBoxes()
{
var allInputs = document.getElementsByTagName('input').length;
var j = 0;
for (i = 0; i <= allInputs; i++)
{
element = document.offerForm[i];
if (element.type == 'radio')
{
if (element.checked == true)
{
j = j + 1;
}
}
}
if (j != 6)
{
alert('All radio buttons has to be checked' +
' before the form can be submitted.');
return false;
}
return true;
}
It works perfectly at the moment.