So I have this JS code, its supposed to output the stuff I put into the email and password boxes on the console, so in the future I can put them into a database.
My problem is, that the first time I execute my code, it works as expected, the second time I do it, the code only displays the last console.log() prompt.
Help will be greatly appreciated.
let email;
let password;
document.getElementById("loginBtn").onclick = function(){
email = document.getElementById("email").value;
console.log(email);
password = document.getElementById("password").value;
console.log(password);
}
<div class="container" >
<h3 id="LogInToAcc" class="fonts"> Log into your account.</h3>
<hr>
<p class="fonts" id="accDont">Don't have an account?</p>
<a class="fonts" id="SignUp" href="signup.html"> Sign up!</a><br><br>
<label class="inputlabel" for="email">Email:</label> <br>
<input id="email" class="inputs" type="email" > <br><br>
<label class="inputlabel" for="password" >Password:</label> <br>
<input id="password" class="inputs" type="password" pattern=".{5,10}"> <br><br>
<a class="forgot" href="newpassword">Forgot your password?</a>
<a href="">
<button id="loginBtn" class="loginBtn" > Login</button> <br><br>
</a>
</div>
<script src="login.js"></script>
Some of the things I tried was, moving the code around. Setting the variables inside the function.
>Solution :
Primarily, your HTML is not valid. After restructuring it and tweaking the JavaScript, you get something like what I’ve got below.
Be sure to read the comments.
// Get you element references just once rather than
// every time the function runs. Also, don't set the
// variables up to point to a property of the element
// so that in case you need to access a different
// property later, you won't need to scan for the
// element reference again.
const email = document.getElementById("email");
const password = document.getElementById("password");
// Set up events the modern way
document.getElementById("loginBtn").addEventListener("click", function(){
console.log(email.value, password.value);
});
<div class="container">
<h1 id="LogInToAcc" class="fonts"> Log into your account.</h1>
<p class="fonts" id="accDont">Don't have an account?</p>
<p><a class="fonts" id="SignUp" href="signup.html"> Sign up!</a></p>
<div><label class="inputlabel" for="email">Email:</label></div>
<div><input id="email" class="inputs" type="email"></div>
<div><label class="inputlabel" for="password" >Password:</label></div>
<div><input id="password" class="inputs" type="password" pattern=".{5,10}"></div>
<div><a class="forgot" href="newpassword">Forgot your password?</a></div>
<div><button id="loginBtn" class="loginBtn" > Login</button></div>
</div>
<script src="login.js"></script>