Reputation: 581
I have the following function. I would like to loops through each var and check if it equals correct.
function checkAnswers(){
DropdownVal1 = $('#dropdown1 option:selected').val()
DropdownVal2 = $('#dropdown2 option:selected').val()
DropdownVal3 = $('#dropdown3 option:selected').val()
DropdownVal4 = $('#dropdown4 option:selected').val()
DropdownVal5 = $('#dropdown5 option:selected').val()
DropdownVal6 = $('#dropdown6 option:selected').val()
DropdownVal7 = $('#dropdown7 option:selected').val()
DropdownVal8 = $('#dropdown8 option:selected').val()
for (var i = 1;i<9;i++)
{
if(DropdownVal+i == "correct"){
console.log("correct" + i)
}
}
}
My console is saying it can't find DropdownVal so I'm assuming it is not concatenating properly with i
How do I concatenate a variable in a loop?
Upvotes: 0
Views: 70
Reputation: 5111
Simply try this:
function checkAnswers(){
for (var i = 1;i<9;i++)
{
if ( $("#dropdown"+i+" option:selected").val() == "correct"){
console.log("correct" + i)
}
}
}
Upvotes: 1
Reputation: 4183
Use Arrays:
function checkAnswers(){
var dropdowns = [ $('#dropdown1 option:selected').val(),
$('#dropdown2 option:selected').val(),
$('#dropdown3 option:selected').val(),
$('#dropdown4 option:selected').val(),
$('#dropdown5 option:selected').val(),
$('#dropdown6 option:selected').val(),
$('#dropdown7 option:selected').val(),
$('#dropdown8 option:selected').val() ];
for (var i = 0;i<dropdowns.length ;i++)
{
if(dropdowns[i] == "correct"){
console.log("correct" + i)
}
}
}
Upvotes: 1
Reputation: 10713
If you want to use DropdownVal and a number you normally use the array datatype. Through which you can iterate by the index. More info about arrays and other datatypes could be found at http://javascript.info/tutorial/array
function checkAnswers(){
var DropdownVal = [];
DropdownVal[0] = $('#dropdown1 option:selected').val()
DropdownVal[1] = $('#dropdown2 option:selected').val()
DropdownVal[2] = $('#dropdown3 option:selected').val()
DropdownVal[3] = $('#dropdown4 option:selected').val()
DropdownVal[4] = $('#dropdown5 option:selected').val()
DropdownVal[5] = $('#dropdown6 option:selected').val()
DropdownVal[6] = $('#dropdown7 option:selected').val()
DropdownVal[7] = $('#dropdown8 option:selected').val()
for (var i = 1;i<9;i++)
{
if(DropdownVal[i] == "correct") {
console.log("correct" + i);
}
}
}
Upvotes: 1
Reputation: 13381
try this
function checkAnswers(){
for (var i = 1;i<9;i++)
{
var val = $('#dropdown'+i+' option:selected').val();
if(val == "correct"){
console.log("correct" + i)
}
}
}
in this case you create dynamic selector and get it value on each loop iterate
Upvotes: 2