简体   繁体   中英

Jquery .val() == ** adding multiple possible answers **

I achived this by doing the following, but as a newbie to javascript and jquery i want to know if there is any shorter way to add multiple 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;

Like

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

by this only validates the last answers in this case AMERICA.

Using $.inArray() :

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

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

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

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

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

In my experience this is actually surprisingly efficient - Javascript is rather good at looking up properties of objects, and it avoids a linear array scan so for larger arrays it's O(log n) instead of O(n) .

Don't use if you've messed with Object.prototype , though!

For the sake of balance, the equivalent non-jQuery way (because 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;
}

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM