Jquery: How To Check If All Radio Buttons In A Div Are Selected
my html looks like this
Solution 1:
$(":radio").change(function() {
var names = {};
$(':radio').each(function() {
names[$(this).attr('name')] = true;
});
var count = 0;
$.each(names, function() {
count++;
});
if ($(':radio:checked').length === count) {
alert("all answered");
}
}).change();
Solution 2:
Restructure your HTML slightly - wrap each radio group in (say) a div. Then you can just do something like this to validate the form when the user submits it:
if ($('div:not(:has(:radio:checked))').length) {
alert("At least one group is blank");
}
Of course this can be tweaked in various ways to suit your HTML. The idea was from Find all radio groups which haven't been selected
Solution 3:
Solution herehttp://jsfiddle.net/QxdnZ/1/
var checked = $("#div1 :radio:checked");
var groups = [];
$("#div1 :radio").each(function() {
if (groups.indexOf(this.name) < 0) {
groups.push(this.name);
}
});
if (groups.length == checked.length) {
alert('all are checked!');
}
else {
var total = groups.length - checked.length;
var a = total>1?' groups are ':' group is ';
alert(total + a + 'not selected');
}
Solution 4:
Validate the form when the user submits it, using this validation code.
var blank = false;
$("input:radio").each(function() {
var val = $('input:radio[name=' + this.name + ']:checked').val();
if (val === undefined) {
blank = true;
returnfalse;
}
});
alert(blank ? "At least one group is blank" : "All groups are checked");
First we get the names of all the radio button groups, then check that each one has a value. (Actually we're doing multiple checks, but that doesn't really matter.)
Solution 5:
Looking for something along these lines? http://jsfiddle.net/gXsZp/3/
<div id="div1">
Q1
<inputtype="radio" name="r1" value="v1" />
<inputtype="radio" name="r1" value="v2" />
<inputtype="radio" name="r1" value="v3" />
<br/>Q2
<inputtype="radio" name="r2" value="v1" />
<inputtype="radio" name="r2" value="v2" />
<inputtype="radio" name="r2" value="v3" />
<br/>Q3
<inputtype="radio" name="r3" value="v1" />
<inputtype="radio" name="r3" value="v2" />
<inputtype="radio" name="r3" value="v3" />
</div>
<br/>
<input id="btn"type="submit" text="submit"/>
$('#btn').click(function(){
if ( $('#div1 input:radio:checked').size() == 3 )
returntrue;
returnfalse;
});
Post a Comment for "Jquery: How To Check If All Radio Buttons In A Div Are Selected"