简体   繁体   中英

Checking if all my Radio Buttons are filled

I need to figure out how to check that my radio buttons are all filled. This is what I have but it only checks one button

    var btns = form.choice_1; 
   for (var i=0; el=btns[i]; i++) {
     if (el.checked) return true;
   }
   alert('Please select a radio button');
   return false;

This is the form that I am taking input from.

<form onsubmit="return checkRadios(this);" name = "form" action = "like.php" method ="post" >


<h1> Questions </h1> 
    <p> Question 1 </p>
    <input type="radio" name="choice_1" value="1">Like <input type="radio" name="choice_1" value="2" > Dislike
     <p> Question 2 </p>
    <input type="radio" name="choice_2" value="1">Like <input type="radio" name="choice_2" value="2" > Dislike
     <p> Question 3 </p>
    <input type="radio" name="choice_3" value="1">Like <input type="radio" name="choice_3" value="2" > Dislike
    <p> Question 4 </p>
    <input type="radio" name="choice_4" value="1">Like <input type="radio" name="choice_4" value="2" > Dislike
    <br> <br>
    <input type="submit" value="Submit">

Any help is appreciated.

Try this:

var checkRadios = function () {
    var btns = form.querySelectorAll('input[name^=choice_][type="radio"]');
    for (var i = 0; i < btns.length; i = i + 2) {
        var check = true;
        if (!btns[i].checked && !btns[i + 1].checked) check = false;
    }
    if (!check) alert('Please select a radio button');
    return check;
}
var form = document.querySelector('form[name="form"]');
form.onsubmit = checkRadios;

Fiddle

You should use jQuery for this. It makes it much easier.

You would do it like this:

var e = ('#[[[[id of your radio]]]]');
if($e.is(':checked'){
//do what you need to
};

Try this. You will need jQuery.

checkRadios = function() {
    if $("input:radio :checked").length == 0 {
        alert('Please select a radio button');
        return false;
    }
}

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