I'm using a variable in Javascript which will be set via Php e.g. var usesInterview = <?php echo 1;?>
If not, then var usesInterview = <?php echo 0;?>
How best should I handle this in my code? There will be a If statement to check for the variable and determine the route to take.
I've tried using typeof() == 1
and when I set it to 0, it still carries out the routine as if it where 1.
I'm using a variable in Javascript which will be set via Php e.g. var usesInterview = <?php echo 1;?>
If not, then var usesInterview = <?php echo 0;?>
How best should I handle this in my code? There will be a If statement to check for the variable and determine the route to take.
I've tried using typeof() == 1
and when I set it to 0, it still carries out the routine as if it where 1.
- Did you find any of the answers usefull? – NilColor Commented Nov 11, 2010 at 7:46
4 Answers
Reset to default 3Why not set it with javascript:
usesInterview = 1;
Even if you set it with PHP, you can check like this:
if (usesInterview === 1){
// variable is equal to 1
}
else if (usesInterview === 0){
// variable is equal to 0
}
Notice the ===
to check for both type as well as value. If you don't want to check for type, you need to use ==
like this:
if (usesInterview == 1){
// variable is equal to 1 or "1" or true
}
else if (usesInterview == 0){
// variable is equal to 0 or "0" or "" or false
}
You should avoid the later approach when you are sure about both type as well as value.
More Information:
- http://w3schools./JS/js_parisons.asp
There are so many ways you can do it... Ie
var usesInterview = <?php echo [0|1];?>
usesInterview ? goingTrueWay() : goingFalsegWay();
or
<?php echo [0|1];?> ? goingTrueWay() : goingFalseWay();
or something like this:
var waysCollection = {
0: function () {...} //routine for usesInterview == 0
1: function () {...} //routine for usesInterview == 1
}
waysCollection[<?php echo [0|1];?>]();
also you can use one of the early suggestion:
if (<?php echo [0|1];?>) {
// truthy branch
} else {
// falsy branch
}
BTW, if you want usesInterview
to be a boolean, yes/no trigger, - use true
/false
not 0
/1
. Its easier to read and understand later. For ex
var usesInterview = <?php echo [false|true];?>
if (usesInterview) {
//do this if `true`
} else {
//do this if `false`
}
typeof
will return the type of the value - "number"
in this case. You're using a non-strict equality check (==
) so "number" == 1
is true
.
Just check the value, using type-strict equality operator (===
):
if (usesInterview === 1) {
// do something
}
else if (usesInterview === 0) {
// do something else
}
Read more about JavaScript parison operators at https://developer.mozilla/en/JavaScript/Reference/Operators/Comparison_Operators.
When usesInterview
is 1 it's truthy. So it's as simple as:
if (usesInterview) {
// truthy branch
} else {
// falsy branch
}