Rubee
Rubee

Reputation: 129

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.

Upvotes: 0

Views: 699

Answers (3)

Drumbeg
Drumbeg

Reputation: 1944

Try this. You will need jQuery.

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

Upvotes: 0

Sergio
Sergio

Reputation: 28845

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

Upvotes: 2

tjons
tjons

Reputation: 4769

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
};

Upvotes: 0

Related Questions