简体   繁体   中英

set of radio button validation using Javascript

I am trying to validate 2 sets of radio button using Javascript. It is working with one set but not when I add another radio set (secondtime visitor). Here is my code:

HTML:

<form name="form1" action="#" method="post"> 
    First time visitor?:<br/>
    <label for="s1">Yes</label>
    <input type="radio" id="radio1" name="firsttime" value="1"/>
    <br/>
    <label for="s2">No</label>
    <input type="radio" id="radio2" name="firsttime" value="2"/>

    <br/>     

    Second time visitor?:<br/>
    <label for="s1">Yes</label>
    <input type="radio" id="radio1" name="secondTime" value="1"/>
    <br/>
    <label for="s2">No</label>
    <input type="radio" id="radio2" name="secondTime" value="2"/>

    <br/>     

    <button type="submit" name="nextBTN" onclick="return validateForm();">Next</button><br/>
</form>

And Javascript code:

function validateForm() {
    var radios = document.getElementsByName("firsttime");
    var radios2 = document.getElementsByName("secondtime");
    var formValid = false;

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

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


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



}

At first glance, I can see that in your second while loop, you still check the radios variable instead of the radios2 variable.

You also used the i variable instead of j in the second loop. And you weren't consistent with the capitalization of secondTime (vs secondtime ).

Here's a working version of your code: http://jsfiddle.net/8edCn/

EDIT: Updated version per your comment: http://jsfiddle.net/8edCn/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM