15

Need to validate a radio button input, i.e. when submit button is pressed and no radio buttons have been selected, it alerts the user saying 'please select a check box', and if a radio button has been selected then simply submit the form, needs no alert.

Can only use HTML CSS and JavaScript for this, I know it's 1000 times easier in jquery but sadly I can't use that.

And I know my HTML isn't valid, but unless it directly affects my current problem then I'll handle it later.

<form name="form1" action="#" onsubmit="return validateForm()" method="post"> 
        
    First time visitor?:<br/>
            <label for="s1">Yes</label>
            <input type="radio" id="1" name="yesno" value="1"/>
            <br/>
            <label for="s2">No</label>
            <input type="radio" id="1" name="yesno" value="2"/>
            
            <br/>       
    
    <input type="submit" value="Submit"><br/>
    </form>

Any pointers are greatly appreciated, thanks.

3
  • 1
    You deleted your question to remake the same one because of negative comments on the other one? Btw, invalid markup (like duplicate ID) does directly affect your current problem. Commented Apr 26, 2012 at 18:17
  • Notice : ids shouldn't start with a number Commented Apr 26, 2012 at 18:17
  • @benji Please post you validateForm function. Commented Apr 26, 2012 at 18:17

6 Answers 6

26

1st: If you know that your code isn't right, you should fix it before do anything!

You could do something like this:

function validateForm() {
    var radios = document.getElementsByName("yesno");
    var formValid = false;

    var i = 0;
    while (!formValid && i < radios.length) {
        if (radios[i].checked) formValid = true;
        i++;        
    }

    if (!formValid) alert("Must check some option!");
    return formValid;
}​

See it in action: http://jsfiddle.net/FhgQS/

Sign up to request clarification or add additional context in comments.

3 Comments

That script should work for more than 2 radio buttons, shouldn't it? I am using your code, but I am getting an error that validateForm() is undefined? What do you think is causing that?
I found what the problem was. I copied it from jsFiddle and adds hidden characters that cause my code to trow an error. Here is the page with more details stackoverflow.com/questions/4404526/…
I would change the line if (radios[i].checked) formValid = true; to if (radios[i].checked) { formValid = radios[i].value; } so it becomes true with the value of the checked item. This way you'll know which item was checked. Also, always use braces, even if there is just one item.
11

Full validation example with javascript:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Radio button: full validation example with javascript</title>
        <script>
            function send() {
                var genders = document.getElementsByName("gender");
                if (genders[0].checked == true) {
                    alert("Your gender is male");
                } else if (genders[1].checked == true) {
                    alert("Your gender is female");
                } else {
                    // no checked
                    var msg = '<span style="color:red;">You must select your gender!</span><br /><br />';
                    document.getElementById('msg').innerHTML = msg;
                    return false;
                }
                return true;
            }

            function reset_msg() {
                document.getElementById('msg').innerHTML = '';
            }
        </script>
    </head>
    <body>
        <form action="" method="POST">
            <label>Gender:</label>
            <br />
            <input type="radio" name="gender" value="m" onclick="reset_msg();" />Male
            <br />
            <input type="radio" name="gender" value="f" onclick="reset_msg();" />Female
            <br />
            <div id="msg"></div>
            <input type="submit" value="send>>" onclick="return send();" />
        </form>
    </body>
</html>

Regards,

Fernando

Comments

7

You could do something like this

var option=document.getElementsByName('yesno');
     
if (!(option[0].checked || option[1].checked)) {
    alert("Please Select Your Gender");
    return false;
}

Comments

2
<form action="" method="post" name="register_form" id="register_form" enctype="multipart/form-data">

    <div class="text-input">
        <label>Gender: </label>
        <input class="form-control" type="radio" name="gender" id="male" value="male" />
        <label for="male">Male</label>
        <input class="form-control" type="radio" name="gender" id="female" value="female" />
        <label for="female">Female</label>
    </div>
    <div class="text-input" align="center">
        <input type="submit" name="register" value="Submit" onclick="return radioValidation();" />
    </div>

</form>

<script type="text/javascript">
    function radioValidation(){

        var gender = document.getElementsByName('gender');
        var genValue = false;

        for(var i=0; i<gender.length;i++){
            if(gender[i].checked == true){
                genValue = true;    
            }
        }
        if(!genValue){
            alert("Please Choose the gender");
            return false;
        }

    }
</script>

Source: http://chandreshrana.blogspot.in/2016/11/radio-button-validation-in-javascript.html

Comments

0
document.forms[ 'forms1' ].onsubmit = function() {
    return [].some.call( this.elements, function( el ) {
        return el.type === 'radio' ? el.checked : false
    } )
}

Just something out of my head. Not sure the code is working.

Comments

0

In addition to the Javascript solutions above, you can also use an HTML 5 solution by marking the radio buttons as required in the markup. This will eliminate the need for any Javascript and let the browser do the work for you.

See HTML5: How to use the "required" attribute with a "radio" input field for more information on how to do this well.

Comments