Adrian Golian
Adrian Golian

Reputation: 41

jquery multiple values

I have this script, in html I have select with option values 1,2,3,4,5 and I want to display/hide other object, but I don't want to use separate codes for each value:

   $('#x').change(function() {   
       $("#xx")[$(this).val() == "5" ? 'show' : 'hide']("fast"); 
   }).change();

What I need is to set more values from val() == "5" to val() == "1,2,3,4,5" but this is not working.

How can I do this?

Upvotes: 1

Views: 1393

Answers (3)

voigtan
voigtan

Reputation: 9031

you could split that string so it becomse a array and use indexOf and implement it on browsers that don´t have it (information is on the page I likned to). Or use jquerys $.inArray method.

Upvotes: 1

Headshota
Headshota

Reputation: 21449

You can use switch:

$('#x').change(function() {   
      var currVal = $(this).val();

switch(currVal){
case 1:
 //your code
      break;    
case 2:
//your code
      break;
case 3:
//your code
      break;
case 4:
//your code
      break;
case 5:
//your code
      break;
   }
});

Upvotes: 0

Jamiec
Jamiec

Reputation: 136114

At its most simple you can just use logical or || for multiple values:

$("#xx")[$(this).val() == "5" || $(this).val() == "4" ? 'show' : 'hide']("fast"); 

But with multiple values this gets very long very quickly. At very least you should store $(this).val() to a variable and compare that:

var val = $(this).val();
$("#xx")[val == "5" || val == "4" ? 'show' : 'hide']("fast"); 

But again this will get long and unwieldly very quickly. A better option is to store an array of the possible values and check if the val() is any of the values in the array:

var values = ["1","2","3","4","5"];
var val = $(this).val();
$("#xx")[$.inArray(val,values) != -1 ? 'show' : 'hide']("fast"); 

Upvotes: 4

Related Questions