Setting Javascript Variable Equal To User Input

Setting Javascript Variable Equal To User Input
0.0 0


The following javascript code is supposed to compare two values entered into two textfields to see if they’re equal. Here is that code:

var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmPassword").value;
var errorMessage = document.getElementById("errorMessage");
var createAccountButton = document.getElementById("createAccount");
var chosenPassord;

createAccountButton.addEventListener("click", function()
												  if(confirmPassword === password)
													  chosenPassword = password;
													  errorMessage.innerHTML = "";
													  console.log("confirmPassword is " + confirmPassword + ",password is " + password);
												  else if(confirmPassword != password)
													  errorMessage.innerHTML = "Passwords don't match!";

That code is in a file called CreateAccount.js and is used with the following html:

<!Doctype html>
		<link href = "SampleProjectCreateAccountPage.css" rel = "stylesheet" type = "text/css"/>
		<div id = "container">
			<div id = "loginContainer">
				<label>Username</label><input id = "username" type = "text" class = "customizeInput"></input> <br/> <br/>
				<label>Email</label><input id = "email" type = "text" class = "customizeInput"></input> <br/> <br/>
				<label>Password</label><input id = "password" type = "password" class = "customizeInput"></input> <br/> <br/>
				<label>Confirm Password</label><input id = "confirmPassword" type = "password" class = "customizeInput"></input> <br/> <br/>
				<p id = "errorMessage"></p>
				<button id = "createAccount" class = "customizeButton" >Create Account</button> <br/> <br/>
				<button id = "cancel" class = "customizeButton" onclick = "location.href = 'SampleProjectLoginPage.html'">Cancel</button>
		<script src = "CreateAccount.js">

My problem is that it always says that password and confirmPassword are equal no matter what you enter. I notice that if you manually set the values to different things in the html it will react to that, which may be part of the problem. However, when I see examples such as this one, it seems as though what I have done should work.

What is going wrong?


password and confirmPassword are set only once, when the page is first loaded. As such, they’re always going to be empty strings. You need to move those variables inside your click handler in order to get the current values.


Do you have any suggestions on how I would do this?


@PortableStick told you where to move your code. Move all of the code at the top to be inside click event’s callback function.