0

Im writing an if statement that allows to display a choice based on users input,

Im basically trying to say if something like if they pick 2-4 guests then allow the option.

This is what i've written:

if (userObj.guests = 2 || userObj.guests <=4 && userObj.dayDifference <=10 ) {
    $('.motel_container').removeClass('disable')
}

How can i only allow the if statement to work if they pick 2 - 4 guests only.

  • 1
    `userObj.guests = 2` using a single `=` is an *assignment*. If you want to check for equality, use `==` or `===`. [In javascript == vs =?](https://stackoverflow.com/questions/11871616/in-javascript-vs) – VLAZ Nov 28 '19 at 06:58
  • Also `userObj.guests == 2 || userObj.guests <=4` doesn't make a lot of sense - `2` is already `<= 4`, as is `1`. So, if you have `userObj.guests = 1`, then `userObj.guests == 2` is `false`, yet `userObj.guests <= 4` is `true`. – VLAZ Nov 28 '19 at 07:02
  • need to fix your conditions as well, should be ```guests >=2 && guests <=4 && diff <=10``` – gvmani Nov 28 '19 at 07:03
  • I think this would help you. Below the new Code: ``` if ((userObj?.guests == 2 || userObj?.guests <= 4) && userObj?.dayDifference <= 10 ) { $('.motel_container').removeClass('disable'); } ``` – Kishan Patel Nov 28 '19 at 07:05

4 Answers4

0

In JavaScript a single '=' is used for assigning a variable, while '==' or '===' are used to compare values.

To check if the user chose between 2 to 4 nights:

if (nights >= 2 && nights <= 4) {
    // do something
}
rrswa
  • 1,005
  • 1
  • 9
  • 23
0

The problem is in the first predicate inside the if statement.

You need to change it from:

userObj.guests = 2

to

userObj.guests == 2
Pingolin
  • 3,161
  • 6
  • 25
  • 40
0
if (userObj.guests >= 2 && userObj.guests <=4 && userObj.dayDifference <=10 ) {
    $('.motel_container').removeClass('disable')
}

This will check if the number of guests is: - greater or equal to 2 - AND smaller or equal to 4 - AND day difference is smaller or equal to 10

PS: I'm confused. You're talking about 2 - 4 nights, but your code is referencing 2 - 4 guests.

Nsevens
  • 2,588
  • 1
  • 17
  • 34
0

You are using assignment operator i.e.(=). if you want to compare then you should use something like (==, >= , <=). In your case, code should be like

if (noofNights >= 2 && noofNights <= 4) {
    // apply code
}