-1

Running into a roadblock with multiple variables and jquery if/then.

What I would like to do is when a user selects a specific state a calculation is done.

This is what I have so far but it is not working:

var zonea = ("NY", "NJ", "DE");

$('#states').change(function () {
var w = +$('#states').val();
if (w == zonea) {
alert("Good!");
}
})

If I change the code to:

var zonea = ("NY", "NJ", "DE");

$('#states').change(function () {
var w = +$('#states').val();
if (w = zonea) {
alert("Good!");
}
})

no matter what state I select the alert is shown.

Am not sure what I am doing wrong here.

penone
  • 742
  • 1
  • 10
  • 27
  • Possible Duplicate? http://stackoverflow.com/questions/11871616/in-javascript-vs – Kevin B May 16 '17 at 19:28
  • Also, `var zonea = ("NY", "NJ", "DE");` doesn't make a whole lot of sense. It is equivalent to `var zonea = "DE";` – Kevin B May 16 '17 at 19:29
  • What I am trying to do is assign multiple states to a var zonea. So that, if a user selects any of the 3 states the alert comes up. – penone May 16 '17 at 19:30
  • if (w = zonea) {... should be if (w == zonea) { – Gerard May 16 '17 at 19:31
  • A variable can only contain one value. Maybe you insted meant for it to contain an array that has multiple values? – Kevin B May 16 '17 at 19:31

2 Answers2

-1

In the second case

var w, zonea;
zonea = false;
if (w = zonea) {
    alert("Good!");
    }

you are assigning the value zonea to w in if condition and so apart from a 0 or a false value for zonea the condition will be true and hence the alert will be executed

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
-1
var zonea = ("NY", "NJ", "DE");
$('#states').change(function () {
var w = +$('#states').val();
if (w = zonea) {
alert("Good!");
}
});

Here you use = which mean assign value and always it will be true to compare two values you have to use == with in your if statement. Also I see that the + sign in var w is not needed and may result in code error, when you define w it will be string and zonea is array so try to use indexOf instead of w==zonea

Osama
  • 2,912
  • 1
  • 12
  • 15