JQuery.val () == ** adding a few possible answers **

I achieved this by doing the following, but as a newbie to javascript and jquery, I want to know if there is a shorter way to add a few possible values.

if ($("input:first").val().toUpperCase() == "UNITED STATES" || $("input:first").val().toUpperCase() == "USA" || $("input:first").val().toUpperCase() == "AMERICA") {
                $("#check").text("Correct!").show().fadeOut(5000);
                return true;

how

if ($("input:first").val().toUpperCase() == ("UNITED STATES","USA","AMERICA")) {
                $("#check").text("Correct!").show().fadeOut(5000);
                return true;

this confirms only the latest answers in this case AMERICA.

+3
source share
4 answers

Using $. inArray () :

if( $.inArray( $("input:first").val().toUpperCase(), [ "UNITED STATES", "USA", "AMERICA" ] ) > -1 ) { ...

Demo: http://jsfiddle.net/4ar2G/

+11
source

You can use an object where keys are required values ​​and an operator in:

var matches = { 'UNITED STATES': 1, 'USA': 1, 'AMERICA': 1 };

if ($("input:first").val().toUpperCase() in matches) {
   ...
}

- Javascript , , O(log n) O(n).

, Object.prototype, !

+4

For balance, the equivalent non-jQuery way (since jQuery doesn't automatically mean better):

if(["UNITED STATES", "USA", "AMERICA"].indexOf($('input:first').val().toUpperCase()) > -1) {
    $("#check").text("Correct!").show().fadeOut(5000);
    return true;
}
+3
source

Try the following:

if($.inArray($("input:first").val().toUpperCase(), ["UNITED STATES","USA","AMERICA"]) > -1){
            $("#check").text("Correct!").show().fadeOut(5000);
            return true;
}
+2
source

All Articles