Skip to content Skip to sidebar Skip to footer

Radio Buttons Post Show Value Even None Of The Buttons Are Checked How To Validate This?

I have a registration form wich has a gender radio option showing male or female. in the HTML none are checked because i want the user to check one. like this:

Solution 2:

The following code will validate your form on the client side This validation will only allow the form to be submitted if one of the gender is selected. If none of the radio button is submitted then it will display an alert message and stop the form from redirecting to action.php.

<form name='whatever' onsubmit='return validate();' method='POST' action='action.php'>
    <label class="radio">
    <input type="radio" name="gender" id="optionsRadios1" onchange='validate()' value="female"> Female
    </label>
    <label class="radio">
    <input type="radio" name="gender" id="optionsRadios2" onchange='validate()' value="male"> Male
    </label>
    <input type='submit' value='submit'>
</form>

<script type='text/javascript'>
    function validate(){
    var feObj=document.getElementById("optionsRadios1");
    var maleObj=document.getElementById("optionsRadios2");
    if (feObj.checked){
        return true;
    }
    if (maleObj.checked){
        return true;
    }
    alert ("Please select a gender");
    return false;
    }   
</script>

Post a Comment for "Radio Buttons Post Show Value Even None Of The Buttons Are Checked How To Validate This?"