Hey there I know it's probably an easy question but I've a problem with my Login/Register in JavaScript. I'm storing the users data via localStorage and when I try to login he always returns my alert message, that the typed in data is wrong.
EDIT: storedName is undefined but password isn't. I still don't get it..
EDIT: Problem solved. Thanks to Hank! Solution is in the comments.
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Learning JavaScript</title>
</head>
<body>
<form id="register-form">
<input id="name" type="text" placeholder="Name" value=""/>
<input id="pw" type="password" placeholder="Password" value=""/>
<input id="rgstr_btn" type="submit" value="get Account" onClick="store()"/>
</form>
<form id="login-form">
<input id="userName" type="text" placeholder="Enter Username" value=""/>
<input id="userPw" type="password" placeholder="Enter Password" value=""/>
<input id="login_btn" type="submit" value="Login" onClick="check()"/>
</form>
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" language="javascript" src="login.js"></script>
</body>
</html>
And here is my JavaScript code:
// Name and Password from the register-form
var name = document.getElementById('name');
var pw = document.getElementById('pw');
// storing input from register-form
function store() {
localStorage.setItem('name', name.value);
localStorage.setItem('pw', pw.value);
}
// check if stored data from register-form is equal to entered data in the login-form
function check() {
// stored data from the register-form
var storedName = localStorage.getItem('name');
var storedPw = localStorage.getItem('pw');
// entered data from the login-form
var userName = document.getElementById('userName');
var userPw = document.getElementById('userPw');
// check if stored data from register-form is equal to data from login form
if(userName.value !== storedName || userPw.value !== storedPw) {
alert('ERROR');
}else {
alert('You are loged in.');
}
}
you have 2 issues:
1. "name" is a reserved word, it's gonna act goffy on you, change it to something else like name1 or nm or something.
2. don't use !==, != will do, you logic is faulty anyways, change it to this:
if(userName.value == storedName && userPw.value == storedPw) {
alert('You are loged in.');
}else {
alert('ERROR.');
}
But yeah, I know you are just practicing, but don't actually save usernames and passwords on the client side.
// entered data from the login-form
var userName=document.getElementById('userName');
var userPw = document.getElementById('userPw');
This is where the issue came to you.
You wanted to compare the entered values with the localStorage data. This is good but it should have been like this:
var userName = document.getElementById('userName').value;
var userPw = document.getElementById('userPw').value;
This is the correct way to get the value of the input field.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>logSign</title>
</head>
<body>
<form id="signup-form">
<input id="name1" type="text" placeholder="Username" value="" required>
<input id="pass1" type="password" placeholder="Password" value="" required>
<input id="signup_btn" type="submit" value="Signup">
</form>
<form id="login-form">
<input id="name2" type="text" placeholder="Username" value="" required>
<input id="pass2" type="password" placeholder="Password" value="" required>
<input id="login_btn" type="submit" value="Login">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#signup-form").submit(function () {
var nm1 = $("#name1").val();
var ps1 = $("#pass1").val();
localStorage.setItem("n1", nm1);
localStorage.setItem("p1", ps1);
});
$("#login-form").submit(function () {
var enteredName = $("#name2").val();
var enteredPass = $("#pass2").val();
var storedName = localStorage.getItem("n1");
var storedPass = localStorage.getItem("p1");
if (enteredName == storedName && enteredPass == storedPass) {
alert("You are logged in!");
}
else {
alert("Username and Password do not match!");
}
});
});
</script>
</body>
</html>
Related
I have the following jsp page, consisting of 2 text fields, 2 password fields, 1 email field and 1 file-uploader, followed by a disabled button:
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<h3>Registration</h3>
<form action="Myservlet" method="POST" enctype="multipart/form-data">
<p>Name <input type="text" name="name" id="name"></p>
<p>Lastname <input type="text" name="lastname" id="lastname"></p>
<p>Email <input type="email" name="email" id="email"></p>
<p>Password <input type="password" name="password" id="password"></p>
<p>Confirm password <input type="password" name="confirmpassword" id="confirmpassword"></p>
<p>Photo <input type="file" name="photo"></p>
<p><input type="submit" value="register" id="register" disabled></p>
</form>
<script src="RegScript.js"></script>
</body>
</html>
My purpose is to enable and disable the button at run time using pure JavaScript, based on 2 conditions:
All the text fields, except the file-uploader, must all be filled in;
The password fields must match.
So I wrote the following JavaScript code:
RegScript.js
name = document.getElementById("name");
lastname = document.getElementById("lastname ");
email = document.getElementById("email");
password = document.getElementById("password");
confirmpassword = document.getElementById("confirmpassword");
register = document.getElementById("register");
//password matching & text fields checking
confirmpassword.addEventListener('input', () =>{
if((name.value.length > 0)&&(lastname.value.length > 0)&&(email.value.length > 0)&&(confirmpassword.value === password.value)){
register.disabled = false;
}
else{
register.disabled = true;
}
});
password.addEventListener('input', () =>{
if((name.value.length > 0)&&(lastname.value.length > 0)&&(email.value.length > 0)&&(confirmpassword.value === password.value)){
register.disabled = false;
}
else{
register.disabled = true;
}
});
The following script seems to work partially, but it has some errors: When I fill in all the text fields in order as they appear, in the moment that the passwords match the button is enabled, as well as if I delete the password it's disabled again, but if instead I delete one of the other three text fields (name, lastname or email) the button remains enabled, when it should not. What can I do to simplify the code (I'm not satisfied with the way I wrote my code, since it's redundant) and to solve to this issue?
You can DRY the validation logic in a validate function that runs whenever inputs change, which is set up using addEventListener on each of them.
This unifies the logic and makes it easy to extend later, for example you might check the emails .validity.valid property to see if it's an actual email.
This is a working snippet:
let name = document.getElementById("name");
let lastname = document.getElementById("lastname");
let email = document.getElementById("email");
let password = document.getElementById("password");
let confirmpassword = document.getElementById("confirmpassword");
let register = document.getElementById("register");
[name, lastname, email, password, confirmpassword].forEach(input => {
input.addEventListener("input", validate)
})
const hasLength = input => input.value.trim().length > 0;
function validate() {
let isValid =
hasLength(name) &&
hasLength(lastname) &&
hasLength(email) &&
hasLength(password) &&
password.value == confirmpassword.value;
console.log(isValid)
register.disabled = !isValid;
}
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<h3>Registration</h3>
<form action="Myservlet" method="POST" enctype="multipart/form-data">
<p>Name <input type="text" name="name" id="name"></p>
<p>Lastname <input type="text" name="lastname" id="lastname"></p>
<p>Email <input type="email" name="email" id="email"></p>
<p>Password <input type="password" name="password" id="password"></p>
<p>Confirm password <input type="password" name="confirmpassword" id="confirmpassword"></p>
<p>Photo <input type="file" name="photo"></p>
<p><input type="submit" value="register" id="register" disabled></p>
</form>
<script src="RegScript.js"></script>
</body>
</html>
JavaScript file is not used in the HTML file despite linking it
I am unable to use the JavaScript file and validate my HTML form. I am wondering if the issue is the linking of the src directory is wrong or could it be that I am missing something in my JavaScript code.
<html>
<head>
<title>Registration Page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/validation.js" type="text/javascript">
</script>
</head>
<body>
<form action="validate" method="post" name="register">
Full Name: <input type="text" name="name" required/><br/> Email Address: <input type="email" name="email" required/><br/> Address Line 1: <input type="text" name="address1" required/><br/> Address Line 2: <input type="text" name="address2" /><br/> Postal Code: <input type="number" name="postal" required/><br/> Mobile Number: <input type="number" name="mobile" required/><br/> Password: <input type="password" name="password" required/><br/> Confirm Password: <input type="password" name="cfpassword"
required/><br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
function validateForm() {
//Use a regular expression to check for the pattern of the password
var regexPass = "^[0-9]{6}[a-zA-Z]{1}$";
var regexMobile = "^[0-9]{8}$";
var regexPost = "^[0-9]{6}$";
//Retrieve the VALUE from the "password" field found in the "register" form
var password1 = document.forms["register"]["password"].value;
var password2 = document.forms["register"]["cfpassword"].value;
var postalcode = document.forms["register"]["postal"].value;
if (matchPost === null) {
alert("The postal code given in the correct format. Please ensure
that is contains exactly 6 digits.
");
// Return false to tell the form NOT to proceed to the servlet
return false;
}
if (matchMobile === null) {
alert("The mobile number given in the correct format. Please ensure
that is contains exactly 8 digits.
");
// Return false to tell the form NOT to proceed to the servlet
return false;
}
// If password not entered
if (password1 == '')
alert("Please enter Password");
// If confirm password not entered
else if (password2 == '')
alert("Please enter confirm password");
// If Not same return False.
else if (password1 != password2) {
alert("\nPassword did not match: Please try again...")
return false;
}
// If same return True.
else {
return true
}
}
If your JS folder is in the same directory as your html file this code should work. Write a simple alert('ahoy') function in your JS file and reload your html to verify if your JS file is loaded or not.
Can anybody tell me why document.getElementById is not detecting the entered password in the code below:
function myFunction() {
let email = "name#email.com";
let password = "password";
if (document.getElementById("password") == password) {
Console.console.log("success");
} else {
console.log("Failure");
console.log(password);
console.log(document.getElementById("password"));
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="#">
<label for="Email">Email</label>
<input id="email" type="email">
<label for="password">Password</label>
<input id="password" type="text">
<button onclick="myFunction()">Submit</button>
</form>
</body>
</html>
When I try to log it's value in the console I just get input id="password" type="text"and I am not sure what this means other than for some reason it is not having the value I want assigned to it.
-Thanks
The function document.getElementById returns a DOM Element Object. This object has various attributes like .style, but to get the text entered for an <input> element, you want the .value attribute.
function myFunction() {
let email = "name#email.com";
let password = "password";
if (document.getElementById("password").value == password){
console.log("success");
} else {
console.log("Failure");
console.log(password);
console.log(document.getElementById("password").value);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="#">
<label for="Email">Email</label>
<input id="email" type="email">
<label for="password">Password</label>
<input id="password" type="text">
<button onclick="myFunction()">Submit</button>
</form>
</body>
</html>
Change these lines
if(document.getElementById("password") == password){
console.log(document.getElementById("password"));
to these lines
if(document.getElementById("password").value == password){
console.log(document.getElementById("password").value);
and Bob's your uncle.
your implementation is ok, but you did a slight mistake. document returns an object with multiple keys. Among those keys 'value' key contains the value of your input field.
document.getElementById("password").value
will return your desired value.
Note: You can access all the attributes from this object. For example
document.getElementById("password").placeholder
will return the hint from the input field
I have been working on this really simple login, where all i want to do is say, if the password is "apple" and password is "123" then link me to another page when i click submit button.
I gave up on the submit button linking portion but i still don't understand why my code won't register, everything looks right to me
<!DOCTYPE html>
<html>
<body>
<form name="loginForm">
<input type="text" name="username" placeholder="Username" value=""/>
<input type="password" name="password" placeholder="Password" value=""/>
<input type="button" name="submit" value="Login" onclick="validate()" />
</form>
<script type="text/javascript">
function validate() {
var user = document.loginForm.username.value;
return user;
var pass = document.loginForm.password.value;
return pass;
if ( (user=="apple") && (pass=="123") ) {
document.write("It worked");
} else {
document.write("Wrong Password");
}
}
</script>
</body>
</html>
Suggestions:
return keyword will exit the function, so the code after return won't be reached. To remove the two 'return' statement is the first step.
document.write will clear the page after document is loaded. You probably need alert function
try using document.getElementById/getElementByName (which is better) instead of document.loginForm...
It is also better to put onsubmit in the form tag (fired after type=submit button is clicked) instead of onclick event for button.
It is better to put Javascript inside the HTML head tag.
Below is a much better/working version:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validate() {
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
if ( (user=="apple") && (pass=="123") ) {
alert("It worked");
return true;
} else {
alert("Wrong password");
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit='javascript:return validate()'>
<input type="text" id="username" placeholder="Username" value=""/>
<input type="password" id="password" placeholder="Password" value=""/>
<input type="submit" value="Login" />
</form>
</body>
</html>
Sorry guys, first time playing around with this. Here's the HTML:
<!DOCTYPE html>
<html>
<head>
<title>SuM BUTtonsS DOe</title>
<link rel="stylesheet" href="buttons.css"/>
</head>
<body>
<p>Please enter the password</p>
<form id="enter" onSubmit="javascript:passCheck()">
<input id="password" type="password" placeholder="Password">
</form>
<p id="incorrect"><em>INCORRECT PASSWORD</em></p>
<script type="text/javascript">
function passCheck() {
var input = document.getElementById('password').value;
if (input == 'herro') {
window.alert("IT WORKS!!");
}
else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
}
}
</script>
</body>
</html>
When I enter the wrong password, INCORRECT PASSWORD comes up, but only for a fraction of a second. Then it's gone again. No idea why.
UPDATE:
<!DOCTYPE html>
<html>
<head>
<title>SuM BUTtonsS DOe</title>
<link rel="stylesheet" href="buttons.css"/>
</head>
<body>
<p>Please enter the password</p>
<form id="enter" onSubmit="javascript:passCheck()">
<input id="password" type="password" placeholder="Password">
</form>
<p id="incorrect"><em>INCORRECT PASSWORD</em></p>
<script type="text/javascript">
function passCheck() {
var input = document.getElementById('password').value;
if (input == 'herro') {
window.alert("IT WORKS!!");
}
else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
return false;
}
}
</script>
</body>
</html>
On submit, the form will trigger the default action, which in this case is to submit the contents to the same page (for lack of an action property).
So what you're seeing is the JavaScript runs and changes the style to show the error message, then the page reloads.
To ensure the page doesn't reload put return false at the end of passCheck. Better would be to use addEventListener and event.preventDefault(), but that's a little bit more involved.
<p>Please enter the password</p>
<form id="enter" onSubmit="passCheck(); return false;">
<input id="password" type="password" placeholder="Password">
<input type="submit" value="Submit"/>
</form>
<p id="incorrect" style="display: none"><em>INCORRECT PASSWORD</em></p>
<script type="text/javascript">
function passCheck() {
var input = document.getElementById('password').value;
if (input == 'herro') {
window.alert("IT WORKS!!");
}
else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
}
}
</script>