I'm trying to write a very simple if statement in my jquery. If the variable equals the number one then do this, if it equals the number two then do this. This is what I wrote but it doesn't seem to work and I can't figure out why:
$("#next-btn").click(function() {
if (current_slide = 1) {
first_screen();
}, else if (current_slide = 2) {
second_screen();
}
});
probably very simple, but I appreciate the help.
I'm trying to write a very simple if statement in my jquery. If the variable equals the number one then do this, if it equals the number two then do this. This is what I wrote but it doesn't seem to work and I can't figure out why:
$("#next-btn").click(function() {
if (current_slide = 1) {
first_screen();
}, else if (current_slide = 2) {
second_screen();
}
});
probably very simple, but I appreciate the help.
Share Improve this question edited Aug 7, 2013 at 18:04 Rich Bradshaw 73k46 gold badges188 silver badges241 bronze badges asked Aug 7, 2013 at 18:01 loriensleafsloriensleafs 2,2559 gold badges37 silver badges71 bronze badges 2 |4 Answers
Reset to default 13You need to use comparison operator ==
in if statement condition instead of assignment operator =
also remove comma
after first closing curly bracket of then
(true) block of if
statement. You can test it over here.
if (current_slide == 1) {
first_screen();
} else if (current_slide == 2) {
second_screen();
}
I assume current_slide has some number to compare, you read below how comparison operator == performs the comparison.
Comparion equal operator
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory, reference.
Use comparison operator "==" instead of assignment "=" and remove comma before else if
.
$("#next-btn").click(function() {
if (current_slide == 1) {
first_screen();
}else if (current_slide == 2) {
second_screen();
}
});
May be it'd be better using switch:
$("#next-btn").click(function() {
switch(current_slide) {
case 1:
first_screen();
break;
case 2:
second_screen();
break;
}
});
Youd shouldn´t check a condition with an assigment:
$("#next-btn").click(function() {
if(current_slide===1){
first_screen();
}else if (current_slide===2){
second_screen();
}
});
current_slide == 1
– Ricardo Lohmann Commented Aug 7, 2013 at 18:02