Writing an If statement to = a number but not allow for than another

80 Views Asked by At

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.

4

There are 4 best solutions below

0
rrswa On

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
}
0
Dan Shmirer On

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

You need to change it from:

userObj.guests = 2

to

userObj.guests == 2
1
nsevens On
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.

0
user8074223 On

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
}