How to format "if val is 1 or 4 or 6 or 10",

I have jquery that validates the value of a form and then does something. It works as expected as follows:

$("#field_1_select_value").bind('change', function (e) { 
  if($("#field_1_select_value").val() == 1){

  // Do stuff

  } else {

  // Do something else

  }         
});

      

I would like to check if the other value has other values, because the behavior will be the same if you select multiple options in the selection, and they will not necessarily be sequential, so I cannot say more or less than X. I want to indicate if you select whether you are, for example, 1, 4, 10 or 20 ... something happens. I tried using commas based on another answer I found elsewhere, for example:

if($("#field_1_select_value").val() == 1, 4, 10, 20){

      

But that didn't seem to work. ,

acts like a multi selector as I understand it and it makes sense in the documentation, but I haven't found much how it can work in an expression script if

like this. I've seen a lot of similar questions, but didn't indicate anything to use in if

using val

.

Thanks for your input and suggestions.

+3


source to share


4 answers


arrays have an indexOf property that you can use. Just remember to convert the value from field_1_select_value

to a number, not the string you would otherwise return.

The fastest way to do this is with the unary operator +

.



if([1, 4, 10, 20].indexOf(+$("#field_1_select_value").val()) >= 0){

      

+12


source


The switch dongle can meet your needs:



switch (parseInt($("#field_1_select_value").val(), 10)) {
case 1:
case 4:
case 10:
case 20:
    // do stuff
    break;
default:
    // do something else
    break;
}

      

+8


source


You can also use jQuerys inArray :

if($.inArray(+$('#field_1_select_value').val(), [1, 4, 10, 20]) > -1)

      

Fiddle

+1


source


maybe you could try something like this:

// this way it easy to insert new values in case of possible 
// changes in the future
var posNums = [1,2,3,4]; 
var val = $("#field_1_select_value").val()

if(posNumbs.indexOf(val) >= 0){
  //some actions
}{
  //other actions
}

      

0


source







All Articles