Need help with checking radio buttons

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Need help with checking radio buttons

Post 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?
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
pbs
Forum Contributor
Posts: 230
Joined: Fri Nov 07, 2008 5:31 am
Location: Nashik, India
Contact:

Re: Need help with checking radio buttons

Post 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;
    }
}
 
 
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Need help with checking radio buttons

Post by social_experiment »

Thank you :)
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply