Amelia
Amelia

Reputation: 320

Determine whether all radio button groups have one checked box

I am making a quiz where each question has a group of radio buttons, like this:

<input type="radio" name="quid16" value="answid53" />Answer 1 : foo
<input type="radio" name="quid16" value="answid54" />Answer 2 : bar
<input type="radio" name="quid16" value="answid55" />Answer 3 : joe
<input type="radio" name="quid16" value="answid56" />Answer 4 : blogs

Each group gets an id, such as quid16 above; this id is generated by PHP and not fixed.

When I validate the form submission, I need to check whether all the groups have one checked radio button.

The problem is that I don't know the group ids beforehand. How would I solve this problem?

Upvotes: 1

Views: 1391

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173542

You can take all radio boxes, starting with "quid", and then:

  1. filter the unique names
  2. filter the checked values
  3. compare 1. vs 2.

Code:

var radios = $('[name^=quid]'),
names = $.unique(radios.map(function() {
    return this.name;
})),
checked = radios.filter(function() {
    return this.checked;
});

if (names.length == checked.length) {
    alert('all answers are checked');
}

Upvotes: 7

Aaron Blenkush
Aaron Blenkush

Reputation: 3059

Use the Attribute Starts With Selector to get elements prefixed with 'quid', and jQuery.is to select elements that are :checked. For example:

$('[name^=quid]').is(':checked'); //Returns true if any radio buttons are 'checked'

Here's an example JSFiddle: http://jsfiddle.net/SDXSf/

<input type="radio" name="quid16" value="answid53" />Answer 1 : foo <br/>
<input type="radio" name="quid16" value="answid54" />Answer 2 : bar <br/>
<input type="radio" name="quid16" value="answid55" />Answer 3 : joe <br/>
<input type="radio" name="quid16" value="answid56" />Answer 4 : blogs <br/>
<br/>
<button>Test</button>
<script type="javascript">
    $(function(){

    function isOneChecked(selector)
    {
       return $(selector).is(':checked')
    }

    $('button').click(function(){
        alert(isOneChecked('[name^=quid]') ? 'Validated' : 'Please select a radio    button');
    });
});
</script>

Upvotes: 0

starowere
starowere

Reputation: 113

if ($('input:radio').is(':checked')) {function()} else {function()}

Upvotes: -1

Related Questions