Reputation: 320
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
Reputation: 173542
You can take all radio boxes, starting with "quid", and then:
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
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
Reputation: 113
if ($('input:radio').is(':checked')) {function()} else {function()}
Upvotes: -1