3

I have some jquery checking the choice made in a drop down.

function toggleFields() {
if ($("#chosenmove1").val() == 4)
    $("#hideme").show();
else
    $("#hideme").hide();
}

This works fine but I would like to change it so it checks a list of values like

if ($("#chosenmove1").val() in (3,4,5))

How can I write this to make it work (the above doesn't)

Tried a bit more

var arr = [3,4,5];
var value = $("#chosenmove1").val();
alert(value);

if ($.inArray(value, arr) > -1)
    $("#hideme").show();
else
    $("#hideme").hide();

}

The alert box tells me var value is getting the right value from the drop down - yet the show hide wont work under this setup. IF I replace var value = $("#chosenmove1").val(); with var value = 3; then it does work?

user1479891
  • 139
  • 1
  • 2
  • 15

2 Answers2

3

Below is my working code: the array numbers needed to be in quotes?

function toggleFields() {
var arr = ['3','4','5'];
var value = $("#chosenmove1").val();

if (jQuery.inArray(value, arr) > -1)
    $("#hideme").show();
else
    $("#hideme").hide();

}
user1479891
  • 139
  • 1
  • 2
  • 15
  • 1
    This answer is actually better if you're using strings. `arr.indexOf` does not seem to play nice with strings in @Richard Macarthy's answer. – Bing Jun 14 '18 at 23:28
1

You can use indexOf

var arr=[1,2,3];

if(!arr.indexOf(1)){ // Your value here
    alert("exists");
}

https://jsfiddle.net/xkcd8vko/1/

rjmacarthy
  • 2,164
  • 1
  • 13
  • 22