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?

4

2 Answers 2

5

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();

}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

You can use indexOf

var arr=[1,2,3];

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.