简体   繁体   中英

Javascript skipping the if and if else conditions and directly jumping to else condition

I am new to JavaScript and just trying my hands on to JavaScript with a simple login page.

I have created a login page using HTML and CSS and JavaScript for validations. But my JavaScript code is not working properly.

It is skipping the if conditions and directly jumping to else part and sometimes it is just validating the first if else part for username validation.

Below is my JavaScript and html code. I am using and external JavaScript.

  function ValidateSignIn() { //Variable declarations and initialization var username = document.getElementsByName("username").value; var password = document.getElementsByName("password").value; //Validation of username and password fields if (username == "Temp" && password == "123") { alert("Login Successful!!"); window.location = "C:\\Users\\metyagi\\Downloads\\Personal data\\THE SCM QUIZ\\WelcomePage.html"; } else if (username == null || username == "") { alert("Please enter CEC ID"); } else if (password == null || password == "") { alert("Please enter Password"); } else { alert("Username or Password is incorrect, Please try again!!"); } } 
 <!doctype html> <html> <head> <meta charset="utf-8"> <title>The SCM Quiz Login Page</title> <link rel="stylesheet" type="text/css" href="css\\SignIn.css" /> <script type="text/javascript" src="C:\\Users\\mt\\Downloads\\data\\test\\SignIn.js"></script> </head> <body> <!--Div for Logo--> <Div class="logo"> <img src="images\\logo.png" /> </Div> <!--Div for form--> <Div class="loginform"> <h3>Login </h3> <h6>Required fields are marked with *</h6> <form method="post" action="" name="SignIn"> <INPUT TYPE="text" name="username" placeholder="Please Enter Username*"> </br> </br> <INPUT TYPE="password" name="password" placeholder="Please Enter Password*"> </br> </br> <INPUT TYPE="submit" name="SignIn" value="SIGN IN" onclick="ValidateSignIn()"> <a href="ForgotPassword.html">Forgot Password?</a> <p class="message">Not Registered Yet? <a href="SignUp.html">Sign Up!</a> </P> </form> </Div> </body> </html> 

You are using document.getElementsByName("username") method ,From the name (get Elements ByName) of the method itself you come to know that it returns the nodelist collection with name as username. so you need to give correct index number to get the value. otherwise you can also use the getElementById() method by defining id for text field in Html.

 function ValidateSignIn() { //Variable declarations and initialization var username = document.getElementsByName("username")[0].value; var password = document.getElementsByName("password")[0].value; //Validation of username and password fields if (username == "Temp" && password == "123") { alert("Login Successful!!"); window.location = "C:\\Users\\metyagi\\Downloads\\Personal data\\THE SCM QUIZ\\WelcomePage.html"; } else if (username == null || username == "") { alert("Please enter CEC ID"); } else if (password == null || password == "") { alert("Please enter Password"); } else { alert("Username or Password is incorrect, Please try again!!"); } } 
 <html> <head> <meta charset="utf-8"> <title>The SCM Quiz Login Page</title> <link rel="stylesheet" type="text/css" href="css\\SignIn.css" /> <script type="text/javascript" src="C:\\Users\\mt\\Downloads\\data\\test\\SignIn.js"></script> </head> <body> <!--Div for Logo--> <Div class="logo"> <img src="images\\logo.png" /> </Div> <!--Div for form--> <Div class="loginform"> <h3>Login </h3> <h6>Required fields are marked with *</h6> <form method="post" action="" name="SignIn"> <INPUT TYPE="text" name="username" placeholder="Please Enter Username*"> </br> </br> <INPUT TYPE="password" name="password" placeholder="Please Enter Password*"> </br> </br> <INPUT TYPE="submit" name="SignIn" value="SIGN IN" onclick="ValidateSignIn()"> <a href="ForgotPassword.html">Forgot Password?</a> <p class="message">Not Registered Yet? <a href="SignUp.html">Sign Up!</a> </P> </form> </Div> </body> </html> 

Basically you want to add some validation for your username and password. What you have written in the first if statement is to validate if both are valid and that should be working correctly.

 else if(username == null || username == ""){
    alert("Please enter CEC ID");       
}

This will stop further evaluation if username is not valid. In case you want to check if password too is not valid, you will need to write in a different if /else block and not in continuation of the username validation.

You are using document.getElementsByName and according to your code you will get undefined in username and password . So you need to do this:

function ValidateSignIn()
{   
    //Variable declarations and initialization
    var username = document.getElementsByName("username")[0].value;
    var password = document.getElementsByName("password")[0].value;

    //Validation of username and password fields
    if(username == "Temp" && password == "123")
    {
        alert("Login Successful!!");
        window.location = "C:\Users\metyagi\Downloads\Personal data\THE SCM QUIZ\WelcomePage.html";     
    }
    else if(username == null || username == "")
    {
        alert("Please enter CEC ID");       
    }
    else if (password == null || password == "")
    {
        alert("Please enter Password");     
    }   
    else
    {
        alert("Username or Password is incorrect, Please try again!!");
    }
}

UPDATE1:

If you want to prevent fields not to clear on submit you can do use preventDefault method of the event object like this:

$("#Formid").submit(function(event){
   event.preventDefault()
})

OR

$("#Formid").submit(function(event){
      e.returnValue = false;
    })

try this :

var username = document.getElementsByName("username")[0].value;
var password = document.getElementsByName("password")[0].value;

or set id on your elements and try :

var username = document.getElementById("username").value;
var password = document.getElementById("password").value;

You should separate validating user input and checking user credentials to make the code clear and easy to read, please refer the code below:

function ValidateSignIn(){
    var hasError = false;

    //Variable declarations and initialization
    var username = document.getElementsByName("username")[0].value;
    var password = document.getElementsByName("password")[0].value;

    //Validation of username and password fields
    if (!username) { // this will check null, undefined, and empty string
        hasError = true;
        alert("Please enter CEC ID"); 
    } else if (!password) {
        hasError = true;
        alert("Please enter Password");
    }

    if (!hasError) {
        if(username == "Temp" && password == "123"){
            alert("Login Successful!!");
            window.location = "C:\Users\metyagi\Downloads\Personal data\THE SCM QUIZ\WelcomePage.html";     
        } else {
            alert("Username or Password is incorrect, Please try again!!");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM