FYI: this is for a simple quiz with just a single input field for each answer.
I have the following Javascript if statement to check if the value entered into an input field is correct (in this case, if the value entered is 'england').
$('input').keyup(function () {
if ($(this).val().toLowerCase() == 'england') {
//Stuff
} else {
//Other Stuff
};
});
However, I want to allow for alternative spellings, so I need a few possible answers for each question - it seems sensible to use an array for this as so...
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
How can I change my if statement to say 'if the input field value equals any of those values from the array, then do the following'?
Any help would be greatly appreciated! Thank you.
You can do this using .inArray()
:
if ($.inArray($(this).val(), ans1) > -1) {
//Stuff
}
Here, the code $.inArray($(this).val(), ans1)
will search for a specified value for example England
within an array ans1
and return its index (or -1 if not found).
UPDATE
For case-sensitive search:
JS:
if ($.inArray($(this).val().toLowerCase(), ans1) > -1) {
//Stuff
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With