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.
2 Answers 2
There's a data structure commonly used for that type of problems : arrays. They're much more suited to your problem than having a bunch of variables.
Supposing you have an array a, you can do
for (var i=1; i<=8; i++) {
(function(answers){
$('.q'+i).keyup(function () {
if ($.inArray($(this).val().toLowerCase(), answers) > -1) {
$('#r').text('ok');
} else {
$('#r').text('not ok');
};
});
})(a[i-1]);
}
Your array would be initialized like this :
var a = [];
a.push([
"egypt"
]);
a.push([
"brasil",
"brazil"
]);
7 Comments
Change this: var a1 = new Array(); a1[0] = "egypt";
var a2 = new Array();
a2[0] = "brasil";
a2[1] = "brazil";
to this:
var a = new Array();
a.push(["egypt"]);
a.push(["brasil","brazil"]);
So that
a[0][0] == a0[0] == "egypt"
a[1][0] == a1[0] == "brasil"
a[1][1] == a1[1] == "brazil"
Then the if statement becomes:
for (var i=1; i<=8; i++) {
$('.q'+i).keyup(function () {
if ($.inArray($(this).val().toLowerCase(), a[i-1]) > -1) {
//Stuff
} else {
//Other stuff
};
});
}
1 Comment
Explore related questions
See similar questions with these tags.
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!