javascriptif-statementoperand

Using AND/OR in Javascript IF Statements


I am trying to make an IF statement in Javascript with the the following code:

     <input class="entry" id="modalod" type="text" placeholder="Enter online ID" name="id" required>
     <input class="entry" id="pass1" type="password" placeholder="Enter Passcode" name="psw" required>
     <input class="entry" id="pass2" type="password" placeholder="Repeat Passcode" name="psw-repeat" required>
     <input class="entry" id ="emailtext" type="text" placeholder="Enter Email" name="email" required>
     <a href="#" class="loginbtnanchor btn btn-primary btn-md" 
     onclick="listids()">Login <i class="fa fa-sign-in"></i></a>

     var modalok = document.getElementById("modalok");
     var idarray = [];
     var passcodearray = [];
     var emailtextarray = [];
     var od = document.getElementById("modalod").value;
     var pass1 = document.getElementById("pass1").value;
     var pass2 = document.getElementById("pass2").value;
     var emailtext = document.getElementById("emailtext").value;
     var at = emailtext.indexOf("@");
     var period = emailtext.indexOf(".");

     modalok.addEventListener("click", function(event) {

        if ( ( (at == -1) || (period == -1) )  && ( (od.length < 15) || 
           (od.length > 18) ) )
        {
            alert("NOTE: ONLINE ID MUST BE BETWEEN 15 AND 18 NUMBERS 
            LONG.\nPASSCODES DON'T MATCH.\nEMAIL INVALID.");
             event.preventDefault();

        }
        else {
           idarray.push(od);
           passcodearray.push(pass1);
           emailtextarray.push(emailtext);


            }
       }); 

What's supposed to happen is that ONLY if BOTH the "user" enters an invalid email AND a wrong id then the alert box appears. However, if just 1 of those conditions happens, the alert box appears. I am thinking the problem is with my syntax in using the AND/OR in this IF statement. I tried switching the order of the AND/OR and the conditions, but still couldn't fix it.

Could I please get help on this?

Thanks,


Solution

  • Move these lines inside the click handler:

    var od = document.getElementById("modalod").value;
    var pass1 = document.getElementById("pass1").value;
    var pass2 = document.getElementById("pass2").value;
    var emailtext = document.getElementById("emailtext").value;
    var at = emailtext.indexOf("@");
    var period = emailtext.indexOf(".");
    

    As it stands, you're getting those values immediately (probably on page load). So, for example, od.length is always 0 and at is always -1, etc.

    A good way to have debugged this yourself would have been to add a console.log right above the if statement to look at the values you were testing. (E.g. console.log(at, period, od);.) This would have made it clear that those values were incorrect, which would have pointed you in the direction of figuring out where those values were coming from.