I do not 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 resolve this?
I do not 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 resolve this?
In JavaScript there is no isset()
. In PHP isset()
has two functionalities: / p>
null
To check if the variable is declared in JavaScript you must use typeof
.
typeof
is a method that says what is the type of the variable, apparently not exactly what you want. But if you use typeof foo != 'undefined';
then you already 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 isset()
checks, ous whether the value of the variable is different from null
, you can do a simple check if(n1 != null){ // fazer algo
.
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 prefer to change undefined
to null
in some situations, everything will depend on the value that is received in the variable through the Javascript debug in the browser.
EDIT
If values pass as a text, or rather as String in the function, you can compare it with double or single quotation marks. Example:
if ((n1 != '') && (n2 != '')){
// Resto do código após verificar se ambas as variáveis estão ou não vazias
}