1

I am a little new to jQuery but I was wondering if there was a way to add multiple values to this:

if ($(this).find(":selected").attr('value') == "196")

Instead of having just "196" can I have an array of possible values?

Huangism
  • 16,278
  • 7
  • 48
  • 74
Shaazaam
  • 102
  • 1
  • 11
  • What is this? I'm guessing a `` with ` – War10ck Jul 31 '14 at 18:09
  • possible duplicate of [jQuery: Adding two attributes via the .attr(); method](http://stackoverflow.com/questions/13014317/jquery-adding-two-attributes-via-the-attr-method) – bencripps Jul 31 '14 at 18:10
  • 1
    You can check if the value is contained in an array of values, sure, by writing JavaScript. – Dave Newton Jul 31 '14 at 18:11
  • 1
    Try `if($.inArray($(this).find(":selected").attr('value'), [196, 200, 105]) > -1)`. – gen_Eric Jul 31 '14 at 18:12
  • jQuery getter methods (such as `.attr("attributeName")`) only return the value of the first item in the collection. you're probably better off using .filter and inArray if it's possible for more than one to be selected. – Kevin B Jul 31 '14 at 18:13
  • It is a select with options yes. Rocket Hazmat: that solution worked perfectly. My followup question is will it take a variable that contains all the values I wish to use? – Shaazaam Aug 01 '14 at 12:41
  • I figured it out. Thank you for the help. – Shaazaam Aug 01 '14 at 13:02

1 Answers1

1

You want to find out if the value of the selected input is one of several possibilities, correct? You can create an array of possibilities and use indexOf to see if your value matches any of them.

var selectedValue = $(this).find(':selected').attr('value'),
    possibilities = [196, 666, 907];

selectedValue = +selectedValue; // coerce the value to a number

if(possibilities.indexOf(selectedValue) !== -1) {
    // Your selected value matches one of the possibilities
} else {
    // Your selected value does not match any of the possiblities
}
cvializ
  • 616
  • 3
  • 11