How to select all checkboxes that are denoted by a two dimensional array?
<div class="Q">
<div id="Q1"><span>1. </span>Which of the following have the same meaning?</div>
<div class="A"><input type="checkbox" id="Q1A1Correct" /><input type="checkbox" id="Q1A1User" class="UserA"/><span id="Q1A1Text">String</span></div>
<div class="A"><input type="checkbox" id="Q1A2Correct" /><input type="checkbox" id="Q开发者_JAVA百科1A2User" class="UserA"/><span id="Q1A2Text">string</span></div>
<div class="A"><input type="checkbox" id="Q1A3Correct" /><input type="checkbox" id="Q1A3User" class="UserA"/><span id="Q1A3Text">Integer</span></div>
<div class="A"><input type="checkbox" id="Q1A4Correct" /><input type="checkbox" id="Q1A4User" class="UserA"/><span id="Q1A4Text">int</span></div>
</div>
And I also have a two dimensional array which denotes the type of each question and it's correct answers, e.g.
var correctAnswers=[["multipleAnswer","1","2"],["multipleAnswer","2","3"]];
Denotes that questions 1 and 2 (first two element in the array) are multiple answer questions (let's assume that's the only kind), and their correct answers are 1 and 2 for question 1, and 2 and 3 for question 2.
Now I need to check each checkbox which is a correct answer (i.e. for question 1 -Q1A1Correct
and Q1A2Correct
).
I managed doing that for a specific question:
var correctAs={};
correctAs.Q1 = ["checkbox","1","2"];
$('#checkAs').click(function(){
$.each(correctAs.Q1,function()
{
$("#Q1A"+this+"Correct").attr('checked', true);
}); //mark correct As according to array above
});
But I can't generalize my code so that it will work with the two dimensional array.
So my question is - how do I check all correct answers for all questions given the array? (changing the way the array is built is an option if that'll be helpful)
Thanks for your time
var correctAnswers = [["multipleAnswer","1","2"], ["multipleAnswer","2","3"]];
$('#checkAs').click(function(e) {
for (var i = 0, len = correctAnswers.length; i < len; i++) {
for (var j = 0, ln = correctAnswers[i].length; j < ln; j++) {
if (!isNaN(Number(correctAnswers[i][j]))) {
$('#Q' + (i+1) + 'A' + correctAnswers[i][j] + 'Correct')
.attr('checked', true);
}
}
}
});
Demo →
精彩评论