Sorry for the vague question title - unsure how to word this.
Basically, I have the following JavaScript that I want to condense using a for loop.
$('.q1').keyup(function () {
if ($.inArray($(this).val().toLowerCase(), a1) > -1) {
//Stuff
} else {
//Other stuff
};
});
$('.q2').keyup(function () {
if ($.inArray($(this).val().toLowerCase(), a2) > -1) {
//Stuff
} else {
//Other stuff
};
});
You can see that the only change between these two functions is the first class (either .q1 or .q2) and the array name (either a1 or a2). So far, I have done the following...
for (var i=1; i<=8; i++) {
$('.q'+i).keyup(function () {
if ($.inArray($(this).val().toLowerCase(), a1) > -1) {
//Stuff
} else {
//Other stuff
};
});
}
You can see that the first class issue has been solved with the incrementing i variable, but I am unsure how I can make the array value change on each loop so that it goes a1, a2, a3, a4 etc.
Any help would be much appreciated. Thank you.
EDIT
The a1 and a2 refers to arrays...
var a1 = new Array();
a1[0] = "egypt";
var a2 = new Array();
a2[0] = "brasil";
a2[1] = "brazil";
I have an array for each answer to a quiz. In each array are the possible answers to each question.
classto all the elements and hang thekeyupevent off that?a1,a2seem to be logically connected – same data structure, I assume, because otherwise you wouldn’t perform the same actions on them? Then don’t use individual variables with numbers in their names (which in 99.999…% of cases indicates that you’re doing it wrong) – but use an array as data structure for this data as well!