Currently, I am trying to store the email and password that is entered. Below I have the HTML and JS code
let email = document.querySelector(".email");
let password = document.querySelector(".password");
//Storing users email and password
function store()
{
localStorage.setItem('email',email.value)
localStorage.setItem('password', password.value)
}
function checkLogin()
{
//get set stored data
let emailStored = localStorage.getItem('email')
let passwordStored = localStorage.getItem('password')
//data entered from login-form
let emailInput = document.querySelector('.email').value
let passwordInput = document.querySelector('.password').value
if(emailInput != emailStored)
{
let eError = document.querySelector(".email-error-message")
eError.innerHTML = "Please enter valid email address"
}
if(passwordInput != passwordStored)
{
let pError = document.querySelector(".password-error-message")
pError.innerHTML = "Please enter password associated with email address"
}
}
<div class="login-form">
<div class="sign-in">
<h1>Sign In</h1>
<form class="form">
<input class="email" type="email" placeholder="Email Address" required />
<div class="email-error-message"></div>
<input class="password" type="password" placeholder="Password" minlength="6" required />
<div class="password-error-message"></div>
<button class="submit">Sign In</button>
<div class="remember-me">
<input class="checkbox" type="checkbox" />
<span class="remember">Remember me</span>
<span class="need">Need help?</span>
</div>
</form>
<div class="facebook-signin">
<img src="images/facebook_social media_social_icon.png" alt="facebook logo" />
<span class="flogin">Login in with facebook</span>
</div>
<div class="newNetoflix">
<div class="newToNetflix">New to Netflix?</div>
<a class="sign-up" data-uia="login-signup-now">Sign up now.</a>
</div>
<div class="disclaimer">
<span class="protected">This page is protected by Google reCAPTCHA to ensure you're not a
bot. </span>
<button type="submit" class="learn-more">Learn More</button>
</div>
</div>
</div>
My end goal is the following:
when the user inputs their email address and password it is saved
when user clicks the check box of remember me it keeps their email address there, but not their password.
PS: I am aware there needs to be an event listener with the checkbox, saying that when the checkbox is checked keep email when the browser refreshes.
Related
I am trying to change (div.class=loguser)'s innerhtml to the username that has logged in. To get the username, I wrote a function that gets input of username and password from the register_button which is inside (div#register). I wrote an object(addData) which takes the username and password and stores it in an array(datas). After putting it in the array, I made a function where it verifies if the username and password exists in the array. If it does exist, it is suppose the change the innerhtml to the username. But it is not working. And I cant even submit the form while registering.
let datas = [];
const addData = (ev) => {
ev.preventDefault();
let data = {
username: document.getElementById('rusername').value,
password: document.getElementById('rpassword').value
}
datas.push(data);
document.forms[0].reset();
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('register_button').addEventListener('click', addData);
});
function isUserValid(username, password) {
var username = document.getElementById('lusername').value;
var password = document.getElementById('lpassword').value;
for (var i = 0; i < datas.length; i++) {
if (datas[i].username === username &&
datas[i].password === password) {
var name = username;
document.getElementsByClassName('loguser').innerHTML = username;
}
}
}
<body>
<div class="loguser">
<td>
<ul class="nav-area">
<li class="dropdown">User
</li>
</ul>
</td>
</div>
</tr>
</table>
</div>
<div class="wrapper">
<div class="login_box">
<div class="login_header">
<img src="images/alimama.png" alt=""> <br> Login or Register!
</div>
<div id="login">
<form action="" method="POST">
<input id="lusername" type="text" name="lusername" placeholder="Username" required>
<br>
<input id="lpassword" type="password" name="lpassword" placeholder="Password">
<br>
<input type="submit" name="login_button" value="Login">
<br>
Need an account? Register here!
</form>
</div>
<div id="register">
<form action="" method="POST">
<input id="rusername" type="text" name="rusername" placeholder="Username" required>
<br>
<input id="rpassword" type="password" name="rpassword" placeholder="Password" required>
<br>
<input id="register_button" type="submit" name="register_button" value="Register">
<br>
Already have an account? Sign in here!
</form>
</div>
</div>
</body>
isUserValid() shouldn't take username and password as parameters, since it gets them from the inputs. It should take an event parameter, so you can call it as an event listener.
document.getElementsByClassName() returns a NodeList. You need to use [0] to access the first match to set its innerHTML. You could also use document.querySelector(), it just returns the first match.
The login button doesn't have an ID. Add id="login_button" so you can add an event listener to it.
Instead of your loop you can use the find() method to search an array.
let datas = [];
const addData = (ev) => {
ev.preventDefault();
let data = {
username: document.getElementById('rusername').value,
password: document.getElementById('rpassword').value
}
datas.push(data);
document.forms[0].reset();
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('register_button').addEventListener('click', addData);
});
function isUserValid(e) {
e.preventDefault();
var username = document.getElementById('lusername').value;
var password = document.getElementById('lpassword').value;
var found_user = datas.find(d => d.username === username && d.password === password);
if (found_user) {
document.getElementsByClassName('loguser')[0].innerHTML = found_user.username;
}
}
document.getElementById("login_button").addEventListener("click", isUserValid);
<body>
<div class="loguser">
User
</div>
<div class="wrapper">
<div class="login_box">
<div class="login_header">
<img src="images/alimama.png" alt=""> <br> Login or Register!
</div>
<div id="login">
<form action="" method="POST">
<input id="lusername" type="text" name="lusername" placeholder="Username" required>
<br>
<input id="lpassword" type="password" name="lpassword" placeholder="Password">
<br>
<input type="submit" id="login_button" name="login_button" value="Login">
<br>
Need an account? Register here!
</form>
</div>
<div id="register">
<form action="" method="POST">
<input id="rusername" type="text" name="rusername" placeholder="Username" required>
<br>
<input id="rpassword" type="password" name="rpassword" placeholder="Password" required>
<br>
<input id="register_button" type="submit" name="register_button" value="Register">
<br>
Already have an account? Sign in here!
</form>
</div>
</div>
</body>
I have created a login form. I want a JS code that:
If the information on the login page i.e Username and Login is correct, It will proceed to another HTML page.
Simply, I want the page to redirect to another page after successfull login attempt. | With JS
I dont want any PHP or MySql code.
I have tried this code but this doesnt works. On wrong information, it says Invalid information. But on correct info, it refreshes the page and there a ? is visible at te end of the url:
Html:
<form id="form" action="" method="GET">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" id="email" class="form-control" aria-describedby="emailHelp" >
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" id="password" class="form-control" >
</div>
<button type="submit" class="btn btn-outline-success btn-lg shadow" onClick="auth()">Submit</button>
</form>
JavaScript:
function auth() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email === "admin#gmail.com" && password === "user") {
location = location['href'];
// alert("You Are a ADMIN");
} else {
alert("Invalid information");
return;
}
}
I have also used:
window.location.replace("upload.html");
instead of:
location = location['href'];
But still does not works.
A couple of things here. One you're doing a GET with your form rather than doing a POST. You should change that. Second, on your JavaScript call for auth you should pass the event parameter so that the default action of the form will be stopped. Third, you should be using a relative path for your URL within your redirect. Last, You should do a window.redirect() to simulate an HTTP redirect when the function executes.
Here is the code with the updates:
<form id="form" action="post">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email"
id="email"
class="form-control"
aria-describedby="emailHelp" >
<small id="emailHelp"
class="form-text text-muted">
We'll never share your email with anyone else.
</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" id="password" class="form-control" >
</div>
<button type="submit"
class="btn btn-outline-success btn-lg shadow"
onClick="auth(event)">Submit</button>
</form>
<script>
function auth(event) {
event.preventDefault();
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email === "admin#gmail.com" && password === "user") {
window.location.replace("/upload.html");
} else {
alert("Invalid information");
return;
}
}
</script>
I am creating a simple login an sign up form that is used to create a user and store it in the local host. I have got the sign up form working as it should, but when I try and pull the information from the localhost, it just refreshes the page. Im just wondering how I can get the function to work correctly.
Here is my JS:
const signup = (e) => {
let user = {
firstName: document.getElementById("firstName").value,
lastname: document.getElementById("lastName").value,
email: document.getElementById("email").value,
username: document.getElementById("username").value,
password: document.getElementById("password").value,
confirm_password: document.getElementById("confirm_password").value,
};
localStorage.setItem("user", JSON.stringify(user));
console.log(localStorage.getItem("user"));
e.preventDefault();
alert("Signup Successful")
};
function login() {
var stored_username = localStorage.getItem('username');
var stored_password = localStorage.getItem('password');
var username1 = document.getElementById('username1');
var password2 = document.getElementById('password2');
if(username1.value == stored_username && password2.value == stored_password) {
alert('Login Successful.');
}else {
alert('Username or password is incorrect.');
}
}
document.getElementById("login-btn").addEventListener(type = click, login())
And here is my HTML:
<div class="bodyBx">
<section>
<div class="container">
<div class="user signinBx">
<div class="imgBx"><img src="https://images.unsplash.com/photo-1551034549-befb91b260e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" style="width: 400px;" alt="" /></div>
<div class="formBx">
<form>
<h2>Sign In</h2>
<input type="text" id="username2" placeholder="Username" />
<input type="password" id="password2" placeholder="Password" />
<button id = "login-btn" type="submit" onclick="login();">Submit</button>
<p class="signup">
Need an account ?
Sign Up.
</p>
</form>
</div>
</div>
</div>
</section>
<!-- ================= Sign Up Form Start ================= -->
<section>
<div class="container">
<div class="user signupBx" id="section2">
<div class="imgBx"><img src="https://images.unsplash.com/photo-1555680206-9bc5064689db?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" style="width: 400px;" alt="" /></div>
<div class="formBx">
<form role="form" onsubmit="signup(event)">
<h2>Sign Up</h2>
<input type="text" id="firstName" placeholder="First Name" />
<input type="text" id="lastName" placeholder="Last Name" />
<input type="email" id="email" placeholder="example#email.com..." />
<input type="text" id="username" placeholder="Username" />
<input type="password" id="password" placeholder="Password" />
<input type="password" id="confirm_password" placeholder="Confirm Password" />
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
</section>
</div>
Change the type of login button to button from submit, like below
<button id = "login-btn" type="button" onclick="login();">Submit</button>
If type=submit the form is posted to the url specified in the action attribute of the form, else to the same page if action is missing and you will see a page refresh.
Alternate method - You can also try return false; in your login()
Also your addEventListener should be like below, you don't have to provide type = click, the first param is of type string and second param is of type function. Check docs
document.getElementById("login-btn").addEventListener("click", login)
Localstorage can only store text. So you store a stringified object, which is fine, but you're trying to retrieve properties from it which don't exist.
Instead of:
var itm={someField:1};
localStorage.setItem("itm",JSON.stringify(itm));
//then later
localStorage.getItem("someField");
//localstorage doesnt know what someField is
You want:
var itm={someField:1};
localStorage.setItem("itm",JSON.stringify(itm));
//then later
itm = JSON.parse(localStorage.getItem("itm"));
someField = itm.someField
As for the refresh, check this out:
Stop form refreshing page on submit
TL;DR: Add e.preventDefault() in function login() (you'll have to change it to function login(e).
recently started to deal with javascript, now I'm doing a registration page. And at the moment the notification about the incorrect filling of the form is displayed via alert (). How can this be improved so that if you enter incorrectly, you immediately see a hint ?
function valid(form){
var checker = false;
var namePattern = new RegExp("^([A-z]{4,20})$");
var passwordPattern = new RegExp("^[A-z0-9]{4,20}$");
var emailPattern = new RegExp("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,5})$");
var fName = form.fName.value;
var lName = form.lName.value;
var password = form.password.value;
var confirmPassword = form.confirmPassword.value;
var email = form.eMail.value;
if(!namePattern.test(fName)){
checker = "Wrong first name";
}else if(!namePattern.test(lName)){
checker = "Wrong last name"
}else if(!passwordPattern.test(password)){
checker = "Wrong password"
}else if(confirmPassword != password){
checker = "Your passwords do not match"
}else if(!emailPattern.test(email)){
checker = "Wrong email"
}
if(checker){
alert(checker);
}
}
<form action="" method="post" name="submit" onsubmit="valid(this)">
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<span>First Name<label>*</label></span>
<input type="text" name="fName" id="fName" placeholder="Your first name">
</div>
<div>
<span>Last Name<label>*</label></span>
<input type="text" name="lName" placeholder="Your last name">
</div>
<div>
<span>Email Address<label>*</label></span>
<input type="text" name="eMail" placeholder="You email">
</div>
<div class="clear"></div>
<a class="news-letter" href="#">
<label class="checkbox"><input type="checkbox" name="checkbox" checked=" "><i> </i>Sign
Up for Newsletter</label>
</a>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div>
<span>Password<label>*</label></span>
<input type="password" name="password" placeholder="Your password">
</div>
<div>
<span>Confirm Password<label>*</label></span>
<input type="password" name="confirmPassword" placeholder="Confirm your password">
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<input type="submit" name="submit" value="submit"/>
</form>
I will be grateful for help)
I suggest you put on input elements onchange function, for example:
<input type="text" name="fName" id="fName" placeholder="Your first name" onchange='validateInput(e)'>
And then you check in function:
function validateInput(e){
var namePattern = new RegExp("^([A-z]{4,20})$");
const value = e.target.value;
if(!namePattern.test(value)){
alert("Wrong first name");
// But instead of alert I would suggest you change the color of the input element in order for the user to see real time that he is entering wrong thing.
//When he enters correct data, input border should be green. This is much more user friendly
}
}
You can every validation check separately like this...
function firstname(value){
var checker = false;
var namePattern = new RegExp("^([A-z]{4,20})$");
if(!namePattern.test(value)){
checker = "Wrong first name";
}
if(checker){
alert(checker);
}
}
<input type="text" name="fName" id="fName" placeholder="Your first name" onblur="firstname(this.value)">
I suggest you can use jquery validation.
The thing is, you are checking your form on your submit event (which is obviously the event that is trigger when the form is submitted).
You need to add input validation on each of your input fields via certain event listeners.
If you add onchange event listener, your callback validation will fire each time you move your focus to another element (aka blur event).
If you add oninput event listener, your callback validation will fire each time you type something new.
I would recommend taking a look at the answers of this question.
var checker;
function valid(form){
checker = '';
var namePattern = new RegExp("^([A-z]{4,20})$");
var passwordPattern = new RegExp("^[A-z0-9]{4,20}$");
var emailPattern = new RegExp("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,5})$");
var fName = form.fName.value;
var lName = form.lName.value;
var password = form.password.value;
var confirmPassword = form.confirmPassword.value;
var email = form.eMail.value;
if(!namePattern.test(fName)){
checker += "No first name<br/>";
}
if(!namePattern.test(lName)){
checker += "No last name<br/>"
}
if(!passwordPattern.test(password)){
checker += "No password<br/>"
}
if(confirmPassword != password){
checker += "Your passwords do not match<br/>"
}
if(!emailPattern.test(email)){
checker += "No email<br/>"
}
if(checker){
document.getElementById("hint").innerHTML = checker;
}
}
valid(document.getElementById("form"));
<form id='form' action="return false;" method="post" name="submit" oninput="valid(this)" onsubmit=' return false;'>
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<span>First Name<label>*</label></span>
<input type="text" name="fName" id="fName" placeholder="Your first name">
</div>
<div>
<span>Last Name<label>*</label></span>
<input type="text" name="lName" placeholder="Your last name">
</div>
<div>
<span>Email Address<label>*</label></span>
<input type="text" name="eMail" placeholder="You email">
</div>
<div class="clear"></div>
<a class="news-letter" href="#">
<label class="checkbox"><input type="checkbox" name="checkbox" checked=" "><i> </i>Sign
Up for Newsletter</label>
</a>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div>
<span>Password<label>*</label></span>
<input type="password" name="password" placeholder="Your password">
</div>
<div>
<span>Confirm Password<label>*</label></span>
<input type="password" name="confirmPassword" placeholder="Confirm your password">
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div style='color:red' id='hint'></div>
<input type='submit'/>
</form>
Using the oninput event to run every single time a input is changed. More user friendly by displaying a text tip instead of popups, and shows all errors, not just the first one in the if/elseif loop.
P.S: You seem to have forgotten to add the submit button in your code.
EDIT: Also made it check validation as soon as the page loaded up too.
I am working on a project where I need to send my data to the firebase of the form.
Link - http://ietvit.com/hackoff/
Github repo link - https://github.com/vivanks/hackoffproject
But on filling out the form it should pop up alert window and submit the form but when I open the website for the first time it does not do anything when it refreshes instead it starts to work perfectly but not for the first time. Any reason why or any suggestions to prevent.
Example :
I open my website for the first time and fills out the subscribe form but it just simply refreshes the page instead of updating firebase and pop-ing alert window.
My html form -
<form class="contact100-form validate-form">
<div class="wrap-input100 m-b-10 validate-input" data-validate = "Name is required">
<input id="name" class="s2-txt1 placeholder0 input100" type="text" name="name" placeholder="Your Name">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 m-b-20 validate-input" data-validate = "Email is required: ex#abc.xyz">
<input id="email" class="s2-txt1 placeholder0 input100" type="text" name="email" placeholder="Email Address">
<span class="focus-input100"></span>
</div>
<div class="w-full">
<p class="s2-txt3 p-t-18">
And don’t worry, we hate spam too! You can unsubcribe at anytime.
</p><br>
<button id="submitBtn" onclick="submitDetail()" name="submit" class="flex-c-m s2-txt2 size4 bg1 bor1 hov1 trans-04">
Submit
</button>
</div>
</form>
My java script -
var nameText = document.getElementById("name");
var emailText = document.getElementById("email");
var submitBtn = document.getElementById("submitBtn");
const firebaseRef = firebase.database().ref();
function submitDetail(){
var nText = nameText.value;
var eText = emailText.value;
firebaseRef.push().set({
name : nText,
email : eText
});
window.alert("Subscribed Successfully")
}
<div class="wrap-input100 m-b-20 validate-input" data-validate = "Email is required: ex#abc.xyz">
<input id="email" class="s2-txt1 placeholder0 input100" type="text" name="email" placeholder="Email Address">
<span class="focus-input100"></span>
</div>
<div class="w-full">
<p class="s2-txt3 p-t-18">
And don’t worry, we hate spam too! You can unsubcribe at anytime.
</p><br>
<button id="submitBtn" onclick="submitDetail(event)" type="submit" name="submit" class="flex-c-m s2-txt2 size4 bg1 bor1 hov1 trans-04">
Submit
</button>
</div>
</form>
And in js to prevent reload :
function submitDetail(ev){
ev.preventDefault();
var nText = nameText.value;
var eText = emailText.value;
firebaseRef.push().set({
name : nText,
email : eText
});
window.alert("Subscribed Successfully")
}