Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a value matches one of the values from an array in Javascript [duplicate]

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.

like image 804
user2586455 Avatar asked Dec 15 '22 04:12

user2586455


1 Answers

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:

  • First enter all the values in the array in Lower Case
  • Next use the code below:-

JS:

if ($.inArray($(this).val().toLowerCase(), ans1) > -1) {
    //Stuff
}
like image 92
palaѕн Avatar answered Dec 17 '22 17:12

palaѕн