Click here to Skip to main content
15,867,756 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is my function in java script: I'm trying to execute if else statement in javascript but instead of one condition both conditions are getting executed.

JavaScript
var loginDB = firebase.database().ref("login-demi");

document.getElementById("login").addEventListener('submit', perform);
function perform(e) {
  e.preventDefault();
  var vname = document.getElementById("namNew").value;
  var vpassword = document.getElementById("pswd").value;
  loginDB.orderByChild("name" + "password").on("child_added", function (data) {
    var nam = data.val().name;
    var pss = data.val().password;
    if (nam == vname && pss == vpassword) {
      console.log(pss);
    } else {
      console.log(vname);
    }
  });
}


And This is my html code block:

HTML
<div class="alert">Logging In!</div>
<div class="alert1">Try Again</div>
<div class="InputBox">
   <input type="text" id="namNew" placeholder="Name">
</div>
<div class="InputBox">
   <input type="password" id="pswd" placeholder="Password">
</div>


What I have tried:

I'm not able to find error, please help me fix my code
Posted
Comments
Afzaal Ahmad Zeeshan 11-Sep-22 19:50pm    
That's not possible. Can you show a demonstration of where it happens?

It can only happen, when Firebase database is executing the code multiple times, and once the if block executes and second time, else block gets the turn.
Member 15627495 12-Sep-22 7:51am    
because of "data." which pass through as 'one' value , for 2 vars, you have data.
the .on() make a list fetch, so one after the other 'data' is filtered.
one time 'if' return true
second time 'if' return false


for information : a if then else never execute both at one time only.

if you want to verify, put a var inc = 0 , before the sequence of user and password checking,
and in the if, and in the else , write 2 inc = inc +1

you'll see you pass the if 2 times ( at less )

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900