using jquery to find radiobutton groups with no answers
I've been racking my brain to find a better solution to the following situation.
Imagine a page with a LOT of radiobuttons on it, and then having some custom validation highlighting the groups of radiobuttons that haven't been answered.
example html (with some answers preselected):
<input type='radio' name='a' value='1' />
<input type='radio' name='a' value='2' />
<input type='radio' name='a' value='3' />
<input type='radio' name='b' value='1' checked="checked"//>
<input type='radio' name='b' value='2' />
<input type='radio' name='b' value='3' />
<input type='radio' name='c' value='1' />
<input type='radio' name='c' value='2' checked="checked"/>
<input type='radio' name='c' value='3' />
<input type='radio' name='d' value='1' />
<input type='radio' name='d' value='2' />
<input type='radio' name='d' value='3' />
I've already written a bit of jQuery that does what i want, but I just know it can be done better/faster/prettier/more efficiently.
//select all radiobuttons
var $radios = $("input[type='radio']")
//loop through all the radios that are checked
$($radios+":checked").each(function(){
//filter out all radios with the current name, and add something to recognize them with
$($radios).filter("[name='" + $(this).attr("name") + "']").addClass("checked")
});
//find all radios without the class checked, and highlight them
var $unchecked_radios = $($radios + ":not(.checked)").addClass("highlight");
But i'm stuck开发者_JAVA技巧 on how to combine those two, so subtracting the ones that have an answer from the entire population of radios.
(although i suspect there might be a better way to select groups of radiobuttons with the same name)
Any help would be greatly appreciated!
Regards, Casper
I don't know if can help, here is some code :
$(document).ready(function() {
$('input:not(:checked)').each(function() {
if($('input[name='+$(this).attr('name')+']:checked').size() == 0)
{
$(this).addClass('highlight');
}
});
});
With this, you only highlight the unchecked radio of groups that don't have any radio checked yet. Does it fit your need?
How about this?
function is_answered(valueName)
{
var result=$('input[name='+valueName+']:checked').size();
return result > 0;
}
Try this:
var $radios = $("input[type='radio']")
//loop through all the radios that are checked
$radios.filter(":checked")
.each(function(){
//filter out all radios with the current name, and add something to recognize them with
$($radios).filter("[name='" + $(this).attr("name") + "']").addClass("checked")
})
.end()
.filter(":not(.checked)").addClass("highlight");
Depending on the usecase, this might be nicer:
$("input[type='radio']").filter(":not(:checked)").addClass("highlight");
But I do not know if you need the "checked" class for something else too.
精彩评论