espresso_coffee espresso_coffee - 3 months ago 10
Ajax Question

How to execute statement if variable not exist?

I'm working on the project where I have to check if variable exists or is not null, then I have to compare two values if variable exist and check if difference is not greater than 10. If it's greater than 10 I have to alert the message, if it's not I have to proceed to my ajax call. So problem that I have is how I can put everything in one statement that way I can use my ajax call only once. Here is example of my code:

function myFunction(){
var var1 = document.getElementById("myvar1").value;
var var2 = document.getElementById("mayvar2").value;
var var3 = document.getElementById("myvar3").value;

if ((var1.length != 0 && var2.length != 0)&&((dateDiff(var1,var2) > 10 && var3 == ''))) {
alert('It is greater than 10!');
}else{
//Ajax call
}
}


So this is my current function, problem showed up because variable one show's up on the page just in the specific situation(I do not want to go in details about that).In that case if I do not have var1, I'm getting an error that my var1 is
undefined
that make sense because is defined above the if statement. So my question is what would be the best solution for this problem? I tried to put one more if statement that will check if variable exist above my existing if but in that case I would need my ajax call twice, something like this:

function myFunction(){
if (document.getElementById("myvar1")) {
var var1 = document.getElementById("myvar1").value;
var var2 = document.getElementById("mayvar2").value;
var var3 = document.getElementById("myvar3").value;

if((var1.length != 0 && var2.length != 0)&&((dateDiff(var1,var2) > 10 && var3 == ''))){
alert('It is greater than 10!');
}else{
//Ajax call
}
}else{
//Ajax call
}
}


I think that there should not be more than one Ajax call, if anyone can help with this problem please let me know. Thanks in advance.

Answer

Just create var1 like this:

var var1 = document.getElementById("myvar1") && document.getElementById("myvar1").value || ""

function myFunction(){
    var var1 = document.getElementById("myvar1") && document.getElementById("myvar1").value || ""; 
    var var2 = document.getElementById("mayvar2").value;
    var var3 = document.getElementById("myvar3").value;

    if ((var1.length != 0 && var2.length != 0)&&((dateDiff(var1,var2) > 10 && var3 == ''))) {
        alert('It is greater than 10!');
    }else{
        //Ajax call 
    }
}
Comments