Page 1 of 1

Need help with checking radio buttons

Posted: Wed Jan 13, 2010 2:52 am
by social_experiment
I have a html page that lets the user pick one of two radio buttons :

Code: Select all

 
<html>
   <form action="somepage.php" method="post" name="form1" onSubmit="return checkIfRadioIsTicked();"; />
    Input : <input type="radio" name="btn" value="1"  />
    Input1 : <input type="radio" name="btn" value="2" />
    <input type="submit" value="Continue" name="button" />
</form>
</html>
 
The javascript that does the checking :

Code: Select all

 
function checkIfRadioIsTicked()
{
    if ( document.form1.btn[0].checked == false || document.form1.btn[1].checked == false  ) 
    {
        alert('Not checked');
        return false;
    }
    else {
        return true;
    }
}
 
The above code works fine, but the processing page is php, and so the html page should be like the example below if i want to access the post value from $_POST['btn'] as an array.

(example 2)

Code: Select all

 
<html>
   <form action="somepage.php" method="post" name="form1" onSubmit="return checkIfRadioIsTicked();"; />
    Input : <input type="radio" name="btn[]" value="1"  />
    Input1 : <input type="radio" name="btn[]" value="2" />
    <input type="submit" value="Continue" name="button" />
</form>
</html>
 
What should my javascript look like if i want to check whether either of the radio buttons have been checked within the above (example 2) html code?

Re: Need help with checking radio buttons

Posted: Wed Jan 13, 2010 3:04 am
by pbs
You can use this function

Code: Select all

 
function validateRadioCheck(fieldName, msg)
{
    var arr = document.getElementsByName(fieldName);
    var choice = false;
    for(r=0;r<arr.length;r++)
    {
        if (arr[r].checked == true)
            choice = true;
    }
    if (!choice)
    {
        alert(msg);
        arr[0].focus();
        return false;
    }
}
 
 

Re: Need help with checking radio buttons

Posted: Wed Jan 13, 2010 3:13 am
by social_experiment
Thank you :)