Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radio button validation through JavaScript

I have the following form:

<form name="survey1" action="add5up.php" method="post" onsubmit="return validateForm()">
<div id="question">Q1) My programme meets my expectations</div><br />
Always<INPUT  TYPE = 'Radio' Name ='q1'  value= 'a'> 
Usually<INPUT  TYPE = 'Radio' Name ='q1' value= 'b'> 
Rarely<INPUT  TYPE = 'Radio' Name ='q1' value= 'c'> 
Never<INPUT  TYPE = 'Radio' Name ='q1' value= 'd'> 
<input type="submit" value="addData" />
</form>

I am trying to validate whether a Radio button has been selected.

The code I am using:

<script type="text/javascript">
function validateForm()
{
if( document.forms["survey1"]["q1"].checked)
{
    return true;
}

else
{
    alert('Please answer all questions');
    return false;
}
}
</script>

This is not working. Any ideas?

like image 903
Matt Avatar asked Dec 21 '22 14:12

Matt


1 Answers

When using radiobuttons you have to go through to check if any of them is checked, because javascript threats them as an array:

<script type="text/javascript">
function validateRadio (radios)
{
    for (i = 0; i < radios.length; ++ i)
    {
        if (radios [i].checked) return true;
    }
    return false;
}

function validateForm()
{
    if(validateRadio (document.forms["survey1"]["q1"]))
    {
        return true;
    }
    else
    {
        alert('Please answer all questions');
        return false;
    }
}
</script>

Regards

like image 161
Andrea Avatar answered Jan 11 '23 23:01

Andrea