JavaScript Login form document.getElementById is not detecting value - javascript

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

Related

Issue in contact form

I am trying to create a simple form using Javascript, but I am facing an issue while trying to display somethings on the console. The issue here is that whenever I click on the submit button, Nothing is displayed on the console despite giving the command e.preventdefault(). At present I want the text Hello to be displayed on console when it satisfies the condition, but even though the condition is satisfied, nothing is displayed.
Herewith attaching the Javascript and HTML code for the same
const passlength = 10;
const firstname = document.getElementById("firstname");
const lastname = document.getElementById("lastname");
const emailid = document.getElementById("emailid");
const password = document.getElementById("pass");
const confirmpassword = document.getElementById("passconfirm");
const phonenumber = document.getElementById("phno");
const form = document.querySelector(".mainform");
function testfunc() {
console.log(type(emailid));
}
function checkpass(pass) {
if (pass>=passlength) {
console.log("Hello");
}
else{
console.log("Out");
}
}
form.addEventListener('submit',function(e){
e.preventDefault();
checkpass(password);
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register with us</title>
</head>
<body>
<div class="mainform">
<form>
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname"><br>
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname"><br>
<label for="emailid">Email ID:</label>
<input type="email" id="emailid" name="emailid"><br>
<label for="pass">Enter password:</label>
<input type="password" id="pass" name="pass"> <br>
<label for="passconfirm">Confirm password:</label>
<input type="password" id="passconfirm" name="passconfirm"> <br>
<label for="phno">Phone number:</label>
<input type="number" id="phno" name="phno">
<br> <br>
<input type="submit" value="Submit" id="submit">
</form>
</div>
</body>
</html>
The problem is in your If statement. You are comparing a number with an HTML element. You still need these two.
.value returns the value of the html element
https://www.w3schools.com/jsref/prop_text_value.asp
.length returns the length of a string
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/length
This is how you compare two numbers, as you intended.
So your new IF condition must be:
(pass.value.length>=passlength)

My HTML form validator in Javascript doesn't seem to be working

I've written a validator for my HTML although I'm not sure where I'm going wrong.
What I'm trying to do below is determine if there is any text in the "First Name" box altogether. There is underlying css to the code but I believe my issue is surrounding my onsubmit and validate function as nothing in the javascript seems to be running once I click the submit button.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NewPatientForm</title>
<link rel="stylesheet" type="text/css" href="NewPatient.css">
<script>
function validate() {
var invalid = false;
if(!document.Firstname.value.length) {
invalid = true;
}
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false; //to make the text appear
}
return true;
}
</script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
</body>
</html>
Looks like the culprit was your attempt to access Firstname on the document object.
I replaced it with the more standard document.getElementById() method and its working.
Some reading on this: Do DOM tree elements with ids become global variables?
function validate() {
var invalid = false;
if(!document.getElementById('Firstname').value.length) {
invalid = true;
}
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false;
}
return true;
}
#form-error {
display: none;
}
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate()">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
There are a couple of typos, and I'll suggest something else as well. First, a fix or three in the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NewPatientForm</title>
<script>
function validate() {
const invalid = document.getElementById("Firstname").value.length == 0;
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false; //to make the text appear
}
return true;
}
</script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
</body>
</html>
My suggestion is that you also look into built-in HTML form validation attributes. I'm thinking you're reinventing the wheel for things like requiring a non-empty Firstname. Why not this instead of JavaScript?
<input type="text" name="Firstname" id="Firstname" placeholder="First Name" required />
And many others, like minlength="", min="", step="", etc.
Plus there's still a JavaScript hook into the validation system with .checkValidity() so you can let the built-in validation do the heavy lifting, and then throw in more of your own custom aspects too.

JavaScript: Login/Register with localStorage

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>

Why doesn't my form show a validation error?

I am trying to perform a simple task. I want to validate a form or show a message stating 'Please complete the form!' What am I overlooking because all works except the message? How can I achieve this or am I simply just missing something? I have tried placing the script at the top and bottom, but I want on the bottom because I want the page to load faster and not pause for the JS.
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Index</title>
<!--[if it IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![end if]-->
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form action="login.php" method="post" id="loginForm">
<fieldset>
<legend>Login</legend>
<div><label for="email">Email Address</label>
<input type="email" name="email" id="email" required></div>
<div><label for="password">Password</label>
<input type="password" name="password" id="password" required></div>
<div><label for="submit"></label><input type="submit" value="Login →" id="submit"></div>
</fieldset>
</form>
<script src="login.js"></script>
</body>
</html>
JS
function validateForm() {
'use strict';
var email = document.getElementById('email');
var password = document.getElementById('password');
if ( (email.value.length > 0) && (password.value.length > 0) ) {
return true;
} else {
alert('Please complete the form!');
return false;
}
}
function init() {
'use strict';
if (document && document.getElementById) {
var loginForm = document.getElementById('loginForm');
loginForm.onsubmit = validateForm;
}
}
window.onload = init;
If you want to use your own validation instead of the browser's built-in checking for required fields, remove the required attributes from your <input> tags.
DEMO

html5 required attribute custom validation message not working

I have a simple form with two inputs and a submit button. I need to display the message depending on the lang attribute. When I click on submit button it displays the message even though the field is filled with valid data.
<!DOCTYPE html5>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="" method="get">
<input type="text" value="" oninvalid="check(event)" required/>
<input type="text" value="" oninvalid="check(event)" required/>
<input type="submit" value="Save">
</form>
<script type="text/javascript">
function check(e) {
var a=document.documentElement.lang;
var validateMsg=(a=="ar"?"In arabic":"Plz enter on Alphabets");
var input = e.target;
if(input.validity.valid){
return true;
}else{
input.setCustomValidity(validateMsg);
return false;
}
}
</script>
</body>
</html>
check(event) is meaningless. The event parameter is passed internally
checking validity inside the oninvalid handler is useless
If you use only oninvalid, you won't be able to change back the validation message once the user starts filling the field. You should use the change, keyup or keydown event for that, depending on the reactivity you want.
This could work:
<input type="text" value="" onchange="check" required />
// ...
function check(e) {
var input = e.target;
var msg = "";
if(!input.validity.valid) {
var a=document.documentElement.lang;
msg=(a=="ar"?"In arabic":"Plz enter on Alphabets");
}
input.setCustomValidity(msg);
}

Categories