Reputation: 3483
How to validate a set of radio buttons having different name attribute.
For ex:
<div id="divTest">
<ul>
<li><input type="radio" name="rdo0"><span>Good</span></li>
<li><input type="radio" name="rdo0"><span>Average</span></li>
<li><input type="radio" name="rdo0"><span>Bad</span></li>
</ul>
<ul>
<li><input type="radio" name="rdo1"><span>Test</span></li>
<li><input type="radio" name="rdo1"><span>Test 2</span></li>
<li><input type="radio" name="rdo1"><span>Test 3</span></li>
</ul>
</div>
i want to validate that every "ul" should have a selected radio button and get appropriate message in either case.
Upvotes: 0
Views: 2237
Reputation: 26858
If you only have radio buttons:
var $uls = $('#divTest > ul');
if ($uls.find(':checked').length === $uls.length) {
// is valid
If you have other inputs too then it's .find(':radio:checked')
Upvotes: 0
Reputation: 1698
You could try something like this:
var radioChecked = false;
$("ul.ContainsRadios").each(function(ind,ele){
radioChecked = false;
$(ele).children("input[type=radio]").each(function(ind2,ele2) {
if (ele2.checked){
radioChecked = true;
}
});
if(!radioChecked){
$(ele).addClass("ValidatClass");
}
});
the only issue with the above code is you will need to label the UL's that contain the radio inputs, with something like the class i mention in the code.
Upvotes: 0
Reputation: 4544
You should try by yourself...
Anyway, here is an example :
function validate_checkbox() {
var error = false;
$('ul', '#divTest').each(function() {
if ( $('input[type="radio"]:checked', this).length == 0) {
error = true;
}
});
return error;
}
$("#somebutton").on('click', function() {
alert(validate_checkbox() ? 'error' : 'ok');
});
http://jsfiddle.net/yiernehr/mgjwj/3/
Upvotes: 2