tyas
tyas

Reputation: 35

JQuery: How to Use IF statement correctly?

I have confuse how to use IF statement correctly for this case. I have some command like:

if($('#use').val() == "choose") {
        //dialog show
        }

i want if $('#use') value like "boom","choose","foo","bar" can open the dialog. How to write the correct command for this case?


its mean (by logical thinking):

if(#use) value "choose" or "boom" or "foo" or "bar" then dialog show

Upvotes: 2

Views: 14188

Answers (4)

Geoff Appleford
Geoff Appleford

Reputation: 18832

You have an extra parenthesis. "choose")) { should be "choose") {.

if ($('#use').val() == "choose") {
    //dialog show
}

Or splitting it into multiple lines might make the intention clearer.

var canOpenDialog = $('#use').val() == "choose";
if (canOpenDialog) {
    //dialog show
}

UPDATE for your edit. You can use $.inArray to check for multiple values.

var options = ["boom","choose","foo","bar"];

var canOpenDialog = $.inArray(($('#use').val()),options) != -1;
if (canOpenDialog) {
    //dialog show
}

Upvotes: 7

Sylvain
Sylvain

Reputation: 3873

You could also use $.inArray().

It will return the index of the searched string in the chosen Array, else return -1

var values = ["boom","choose","foo","bar"];

if ($.inArray($('#use').val(),values) != -1) {
    // do stuff if "boom" is in the array
} else {
    // do stuff if it is not.
}

Upvotes: 1

Vivek
Vivek

Reputation: 11028

better option is to use $.inArray()

var required= ["boom","choose","foo","bar"];
if ($.inArray(($('#use').val()),required) != -1) {
    // do Whatever you want
}

Upvotes: 0

Krimo
Krimo

Reputation: 954

var useValue = $('#use').val();
if (useValue == "choose" || useValue == "boom" || useValue == "foo" || useValue == "bar") {
  //do stuff
}

Upvotes: 3

Related Questions