How to select all 'checked' checkboxes pairs?
<div id="Question1"><span>1. </span>Which of the following have the same meaning?</div>
<div><input type="checkbox" id="Question1Answer1Correct" /><input type="checkbox" id="Question1Answer1User"/><span id="Question1Answer1">String</span></div>
<div><input type="checkbox" id="Question1Answer2Correct" /><input type="checkbox" id="Question1Answer2User"/><span id="Question1Answer2">string</span></div>
<div><input type="checkbox" id="Question1Answer3Correct" /><input type="checkbox" id="Question1Answer3User"/><span id="Question1Answer3">Integer</span></div>
<div&开发者_运维百科gt;<input type="checkbox" id="Question1Answer4Correct" /><input type="checkbox" id="Question1Answer4User"/><span id="Question1Answer4">int</span></div>
</div>
Now I need to retrieve all answers which their "Correct" and "User" checkboxes are checked - and mark them as correct, all those whose "Correct" and "User" checkboxes are unchecked - and also mark them as correct, and mark all other answers as incorrect.
I was starting to do that like so:
$('#checkAnswers').click(function(){
$.each($("input[id^='Question1Answer1']"),function(){
if ($("#Question1Answer1Correct").attr('checked') && $("#Question1Answer1User").attr('checked') )
{
$('#Question1Answer1').css('color','#00AB32'); //that's green for correct
}
});
But it seems too hard for me to generalize that.
Question is - how do I make this code work for all answers (you can assume of course all answers have the same naming scheme).Thanks for your time!
I think you should be able to achieve this by using .filter()
$('#checkAnswers').click(function() {
$("span").css("color", "");
$("div > :checkbox").parent().filter(function() {
return $(this).find(":checked").length == 2 || $(this).find(":checked").length == 0;
}).find("span").css('color', '#00AB32');
});
Target only checkboxes that are in the div, use .parent()
and then .filter()
to only find the elements that have 0 checks or both checked and simply color the <span/>
.
Example on jsfiddle
精彩评论