4
I don’t know what’s wrong with this Javascript code:
if( (isset(n1)) && (isset(n2)) ){
document.getElementById('resultado').innerHTML = n1 + n2;
}
I think I’m mixing PHP with JS. How can I fix this?
4
I don’t know what’s wrong with this Javascript code:
if( (isset(n1)) && (isset(n2)) ){
document.getElementById('resultado').innerHTML = n1 + n2;
}
I think I’m mixing PHP with JS. How can I fix this?
5
In Javascript does not exist isset()
. In PHP the isset()
has two features:
null
To verify that the variable is declared in Javascript you must use the typeof
.
The typeof
is a method that tells which is the guy variable, apparently not exactly what you want. But if you use typeof foo != 'undefined';
then you’ll have what you want, and typeof
has the advantage of not generating errors if the variable is not declared.
So instead of
if((isset(n1)) && (isset(n2))){
document.getElementById('resultado').innerHTML = n1 + n2;
}
you can use:
if(typeof n1 != 'undefined' && typeof n2 != 'undefined'){
document.getElementById('resultado').innerHTML = n1 + n2;
}
If you also want to check the second condition that the isset()
check, ous is if the value of the variable is different from null
, you can do a simple check if(n1 != null){ // fazer algo
.
-2
if ((n1 != undefined) && (n2 != undefined)){
// Resto do código após verificar se ambas as variáveis estão ou não vazias
}
Or I’d rather trade the undefined
for null
in some situations, everything will depend on the value received in the variable through the Javascript debug in the browser.
EDIT
If the values pass as a text, or rather as String in the function can be compared with double or single quotes. Example:
if ((n1 != '') && (n2 != '')){
// Resto do código após verificar se ambas as variáveis estão ou não vazias
}
Undefined means that the variable is full right? And by the way how to say in javascript q the variable is clean?
undefined
means that the variable is not defined, that is, it has not been assigned value. I will edit the answer according to your question in the comment
sure tell me when the variable is set too.
It will be set when there is a value assigned to it, namely 0.1, when the type is numeric and "Test" or another value if it is a String. To check when this set is used the code I passed you above, as far as I know there is a reserved word like undefined
to check if it is set. So for this you can use the example codes I answered.
This answer is wrong if n1
is not declared: (http://jsfiddle.net/pbm23zge/). You should check
In this case I did the same answer thinking that the variables were declared, but good to know your example below that also unaware.
Browser other questions tagged php javascript
You are not signed in. Login or sign up in order to post.
There is no
isset()
in javascript, only in php.– rray
In case, as would do ?
– Gonçalo
I don’t know what you want to do. Explain more details.
– rray