Functions in document.ready is not working - javascript

I think the Jquery syntax IM using isn't correct, but not sure what is wrong. Maybe someone can give me a hand. So I have a HTML Login page, where it asks for user and pw. I want to save these 2 variables as session cookie.
Here is the HTML of the login:
<FORM NAME="cf">
<span class="auto-style1">Username:</span>
<input type="hidden" id="messageType" name="messageType" value="3">
<INPUT TYPE="text" id="userName" NAME="userName" size="20" style="width: 180px">
<br><span class="auto-style1">Password:</span> <INPUT TYPE="password" id="password" NAME="password" size="20" style="width: 180px">
<span lang="en-ca"> </span>
</FORM>
<INPUT TYPE="submit" id="btnSubmit" name="btnSubmit" Value="Sign In" style="width: 109px" class="auto-style2">
Here is the Javascript I have written:
$(document).ready(function () {
$("#btnSubmit").click(function () {
//collect userName and password
var messageType = $("#messageType").val();
var userName = $("#userName").val();
var password = $("#password").val();
var YouEntered;
var YouEntered2;
var cookie_name1 = "username";
var cookie_name = "password";
putCookie();
putCookie2();
auth(messageType, userName, password);
});
});
//Set Cookies username and password
function putCookie() {
if(document.cookie != document.cookie)
{index = document.cookie.indexOf(cookie_name1);}
else
{ index = -1;}
if (index == -1)
{
YouEntered=document.cf.userName.value;
document.cookie=cookie_name1+"="+YouEntered+"; expires=0"; //Expires when Session Ends
}
}
function putCookie2() {
if(document.cookie != document.cookie)
{index = document.cookie.indexOf(cookie_name);}
else
{ index = -1;}
if (index == -1)
{
YouEntered2=document.cf.password.value;
document.cookie=cookie_name+"="+YouEntered2+"; expires=0"; //Expires when Session Ends
}
}
If I use onclick in the HTML to run the putCookie functions, I can save the cookies, but it won't send to the server.
Any help or reason why it doesn't work is appreciated.

First change your function as
function putCookie(cookie_name1) {
if(document.cookie != your_cookie){
index = document.cookie.indexOf(cookie_name1);
}
else {
var YouEntered=document.cf.userName.value;
document.cookie=cookie_name1+"="+YouEntered+"; expires=0"; //Expires when Session Ends
}
}
and should call the function like
putCookie(cookie_name1);

Related

How to create multiple login and registration form using JavaScript only and storing to the local server

I need some help I have created a login and registration form and its stores its values to the local storage. This is for a class, how can I make it to accept more than one user. Right now it only takes one username and password.
Thanks in advance,
<!-- sign up form -->
<div class="container pt-5">
<!-- registration form -->
<form id="register-form">
<input id="uName" type="text" placeholder="Name" value="" />
<input id="uPw" type="password" placeholder="Password" value="" />
<input id="rgstr_btn" type="submit" value="get Account" onClick="store()" />
</form>
<!-- login form -->
<form id="login-form" action="./index.html">
<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>
</div>
// Name and Password from the register-form
var name = [document.getElementById('uName')];
var pw = document.getElementById('uPw');
// storing input from register-form
function store() {
localStorage.setItem('name', uName.value);
localStorage.setItem('pw', uPw.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 usrName = document.getElementById('userName').value;
var usrPw = document.getElementById('userPw').value;
// check if stored data from register-form is equal to data from login form
if (userName.value == storedName && userPw.value == storedPw) {
alert('You are logged in ' + usrName);
location.replace("./index.html")
} else {
alert('Access denied. Valid username and password is required.');
}
}
You would want to use an array of objects where each objects stores a username and password. However localStorage only stores strings, so the array needs to be encoded and decoded into a string, which can be done by JSON.
The check function would look like:
function check() {
var usrName = document.getElementById('userName').value;
var usrPw = document.getElementById('userPw').value;
let stored_users = JSON.parse(localStorage.getItem('users'))
if(stored_users) {
for (let u = 0; u < stored_users.length; u++){
if (usrName == stored_users[u].name && usrPw == stored_users[u].password) {
alert('You are logged in ' + usrName);
return location.replace("./index.html");
}
}
} else {
localStorage.setItem('users', '[]');
}
return alert('Access denied. Valid username and password is required.');
}
Then store would look like:
function store() {
var usrName = document.getElementById('userName').value;
var usrPw = document.getElementById('userPw').value;
let stored_users = JSON.parse(localStorage.getItem('users'));
if(stored_users) {
stored_users.push({name: usrName, password: usrPw});
localStorage.setItem('users', JSON.stringify(stored_users));
} else {
localStorage.setItem('users', JSON.stringify([{name: usrName, password: usrPw}]));
}
}
You could store an Object at localStorage instead of property. Just parse it into a JSON string like this:
var users = {
userA: {
name: 'usernameA',
pw: 'passwordA'
},
userB: {
name: 'usernameB',
pw: 'passwordB'
}
};
localStorage.setItem('users', JSON.stringify(users));
Then you can iterate over users object:
var users = JSON.parse(localStorage.getItem('users'));
console.log(users.userA);
console.log(users.userB);
I dont't know the context, I suppose security is not an issue, but I would do something like this:
const jsonObject=localStorage.getItem(key);
//"[{\"user\":\"John\",\"password\":\"12345\"},{\"user\":\"Doe\",\"password\":\"password\"}]"
const theObject=JSON.parse(jsonObject);
// [{user:"John",password:"12345"},{user:"Doe",password:"password"}];
theObject.push ({user:"Jerry",password:"tom"});
const updatedJson=JSON.stringify(theObject);
localStorage.setItem(key, updatedJson);

How can I verify form passwords match using JavaScript?

I have a basic html form with password and verify password fields. I want to only allow users to continue if passwords match. If passwords do not match, I want there to be a notification to the user.
I think that what I currently have is close, but the JS still doesn't appear to do anything.
HTML
<form class="ajax-form" id="pwreset" method="post" onsubmit="return verifyPassword()" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username"/><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password"/><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword"/><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}"/>
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
JS
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
There are some issues that can come from putting the javascript call in the HTML.
In your case, the function was probably defined after the HTML, so the element didn't have access to it.
You can use this instead:
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
document.getElementById('pwreset').onsubmit = verifyPassword;
<form class="ajax-form" id="pwreset" method="post" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username" /><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password" /><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword" /><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}" />
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
Here is an example. I created a passwordGroup constructor to centralize the information. This way it's easier to write tests also.
var form = document.forms[0];
var pass1 = form.querySelector('[data-password]');
var pass2 = form.querySelector('[data-password-confirmation]');
var submitButton = form.querySelector('button[type="submit"]');
// PasswordGroup constructor
var PasswordGroup = function () {
this.password = '';
this.passwordConfirmation = '';
};
// method to update the passwords values
PasswordGroup.prototype.setValues = function(data) {
this.password = data.password;
this.passwordConfirmation = data.passwordConfirmation;
};
// method to check the password's equality
PasswordGroup.prototype.match = function() {
return !!(this.password
&& this.passwordConfirmation
&& this.password === this.passwordConfirmation);
};
/*
* Enable/disable the submit button if passwords do not match
*/
function validateSubmit() {
if(passwordGroup.match()) {
submitButton.removeAttribute('disabled');
} else {
submitButton.setAttribute('disabled', 'disabled');
}
}
// passwordGroup instance
var passwordGroup = new PasswordGroup();
// objecto to store the current values
var passwordsValues = {
password: '',
passwordConfirmation: '',
};
// event triggered after enter a new value in the password's field
var onPasswordChange = function(e) {
var target = e.target;
var targetValue = target.value;
if(target.dataset.hasOwnProperty('password')) {
passwordsValues.password = targetValue;
} else if (target.dataset.hasOwnProperty('passwordConfirmation')) {
passwordsValues.passwordConfirmation = targetValue;
}
passwordGroup.setValues(passwordsValues);
validateSubmit();
};
// event attribution
pass1.onkeyup = onPasswordChange;
pass2.onkeyup = onPasswordChange;
input {
display: block;
}
<form action="" name='account'>
<input type="text" placeholder="name" />
<input type="password" data-password placeholder="password"/>
<input type="password" data-password-confirmation placeholder="repeat password"/>
<button type="submit" disabled="disabled">Enviar</button>
</form>
<p data-message></p>

javascript function not getting called on submit

I have written the simple html javascript code for validation of username and password , but the function authorize() is not getting called when the form is submitted. Can any one help me find out the mistake in my code. I know same question exists and I did followed them but I wasn't able to find my mistake. Thank You.
Below is my code
<script type="type/javascript" >
var users = {{"Username":"Sunny","Password":"Panzer"},{"Username":"Anjali","Password":"406460"}};
function authorize()
{
var username= document.getElementById("username").value;
var password = document.getElementById("password").value;
for(var i=0;i<users.length;i++)
{
if(users[i].Username==username && users[i].Password==password)
{
return true;
}
}
alert("invalid username or password");
return false;
}
</script>
<form action="enter_details.html" onsubmit="return authorize()" >
<center>Username <input type="text" id="username"></center><br><br>
<center>Password <input type="text" id="password"></center><br><br>
<center><input type="submit" id="login_button" value="Log In"></center>
</form>
You should enclose your JSON array in square (and not curly) brackets, like this:
var users = [{
"Username": "Sunny",
"Password": "Panzer"
},
{
"Username": "Anjali",
"Password": "406460"
}
];
function authorize() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
for (var i = 0; i < users.length; i++) {
if (users[i].Username == username && users[i].Password == password) {
return true;
}
}
alert("invalid username or password");
return false;
}
<form action="enter_details.html" onsubmit="return authorize()">
<center>Username <input type="text" id="username"></center><br><br>
<center>Password <input type="text" id="password"></center><br><br>
<center><input type="submit" id="login_button" value="Log In"></center>
</form>
We have two probleme here
1- the users mus be an array of object like :
var users = [{"Username":"Sunny","Password":"Panzer"},{"Username":"Anjali","Password":"406460"}];
2- when you insert your javascript code in html it is not : type="type/javascript" but type="text/javascript"
for resume your code must be like :
<script type="text/javascript">
var users = [{"Username":"Sunny","Password":"Panzer"},{"Username":"Anjali","Password":"406460"}];
function authorize()
{
var username= document.getElementById("username").value;
var password = document.getElementById("password").value;
for(var i=0;i<users.length;i++)
{
if(users[i].Username==username && users[i].Password==password)
{
return true;
}
}
alert("invalid username or password");
return false;
}
</script>
I hope it's help you
Try to use event listeners
Add a id attribute to form
<form id="myForm" action="enter_details.html" onsubmit="return authorize()" >
<center>Username <input type="text" id="username"></center><br><br>
<center>Password <input type="text" id="password"></center><br><br>
<center><input type="submit" id="login_button" value="Log In"></center>
</form>
And add event listener code in is
document.querySelector("#myForm")
.addEventListener("submit", function(eve) {
eve.preventDefault();
authorize();
}
If this didn't work try it on input button
document.querySelector("#login_button")
.addEventListener("click", function(eve) {
eve.preventDefault();
authorize();
}
var users = [{"Username":"Sunny","Password":"Sunny"},{"Username":"Anjali","Password":"406460"}];
function authorize(){
var username= document.getElementById("username").value;
var password = document.getElementById("password").value;
for(var i=0;i<users.length;i++)
{
if(users[i].Username==username && users[i].Password==password)
{
return true;
}
}
alert("invalid username or password");
return false;
}
<form onsubmit="authorize()" >
<center>Username <input type="text" id="username"></center><br><br>
<center>Password <input type="text" id="password"></center><br><br>
<center><input type="submit" id="login_button" value="Log In"></center>
</form>
If you want to use the callback function to submit the form, you need bind click on the
submit button and use event.preventDefault(); to prevent the page jumps in the callback, which is the form default action
<form>
<center>Username <input type="text" id="username"></center><br><br>
<center>Password <input type="text" id="password"></center><br><br>
<center><input type="submit" onclick="authorize(event)" id="login_button" value="Log In"></center>
</form>
<script>
var users = [{"Username":"Sunny","Password":"Panzer"},{"Username":"Anjali","Password":"406460"}];
function authorize(event)
{
event.preventDefault();
var username= document.getElementById("username").value;
var password = document.getElementById("password").value;
for(var i=0;i<users.length;i++)
{
if(users[i].Username==username && users[i].Password==password)
{
return true;
}
}
alert("invalid username or password");
return false;
}
</script>
I believe your main is problem is that variable users should be an array. Your current syntax is not valid for the definition of variable users, and will thrown an error (you can inspect the console to see it). Check the next example with that fix.
var users = [
{"Username":"Sunny","Password":"Panzer"},
{"Username":"Anjali","Password":"406460"}
];
function authorize()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
for (var i = 0; i < users.length; i++)
{
if (users[i].Username == username && users[i].Password == password)
{
return true;
}
}
alert("invalid username or password");
return false;
}
<form onsubmit="return authorize()" >
<center>Username <input type="text" id="username"></center><br><br>
<center>Password <input type="text" id="password"></center><br><br>
<center><input type="submit" id="login_button" value="Log In"></center>
</form>
Even more, you can simplify the authorize() function a litle if you use Array.some():
function authorize()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
let res = users.some(user => user.Username == username && user.Password == password);
if (!res)
alert("invalid username or password");
return res;
}

Use JavaScript to change the href Tag depending on input field

I want to make the link in this change depending on whether the password is correct. I want to set one password and I only know html and minimal JS. I think I have it set so that when the password is wima it will change the href and allow the link to work. That doesn’t happen. Can I have some help?
function login()
var password = getElementById("password"); {
if (password = "wima") {
getElementById("submit").href = "/pages/home.html";
} else {
getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type=text placeholder="WIMA"><br> Password
<input id="password" type=password placeholder="WIMA"><br>
<a class="button" id="submit" href="#" onclick="login()">
Submit
</a>
</p>
There are a few issues with your JavaScript.
<script language="JavaScript">
function login()
var password = getElementById("password"); // this gets the element, not the value of the element
{ // this curly brace is in the wrong place
if (password = "wima") { // this sets the value of the password var to "wima"
getElementById("submit").href="/pages/home.html";
}
else {
getElementById("submit").href="index.html";
}
}
</script>
Here is your code, cleaned up.
<script language="JavaScript">
function login() {
var password = document.getElementById("password").value;
if (password == "wima") { // use == to compare value
document.getElementById("submit").href="/pages/home.html";
}
else {
document.getElementById("submit").href="index.html";
}
}
</script>
Another issue here is that you shouldn't be changing the href on the element used to execute the login() function.
You could redirect the user to the new page like so:
<script language="JavaScript">
function login() {
var password = document.getElementById("password").value;
if (password == "wima") {
window.location.href="/pages/home.html";
}
else {
window.location.href="index.html";
}
}
</script>
I guess you are doing it wrong if you want to change the href value based upon input type text. You should make a blur/change event on password input text. Based upon password value when user clicks on href he should be redirected accordingly.
Check this out:
function login() {
var _password = document.getElementById("password").value;
if ("wima" == _password) {
document.getElementById("submit").href = "/pages/home.html";
} else {
document.getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type=text placeholder="WIMA">
<br> Password
<input id="password" type=password placeholder="WIMA" onblur="login()">
<br>
<a class="button" id="submit" href="#">
Submit
</a>
</p>
Here is a form validator with a switch.
function validateForm() {
var x = document.forms["myForm"]["password"].value;
switch (x) {
case "":
alert("Name must be filled out");
return false;
break;
case "wima":
return true;
break;
default:
alert("Error: Wrong Password.");
document.location.href = "https://stackoverflow.com/search?q=notloggedin";
// Replace the link above with your error link return
return false;
}
}
<!-- Replace action link with your successful link -->
<form name="myForm" action="https://stackoverflow.com/search?q=login" onsubmit="return validateForm()" method="post">
<input type="password" name="password">
<input type="submit" value="Submit">
</form>
Your password is visible in text if someone inspects the html/javascript. So this method of security is not advised. For basic concepts it is interesting to have a link change based on input. Try this.
<p>
Username
<input id="username" type="text" placeholder="WIMA"><br> Password
<input id="password" type="password" placeholder="WIMA"><br>
<a class="button" id="submit" >
Submit
</a>
</p>
<script>
var password = document.getElementById('password');
password.addEventListener('change', enableLogin);
var submit = document.getElementById('submit');
function enableLogin() {
if (password.value == "wima") { // it is an easy mistake (= or ==)
submit.href = "/pages/home.html";
} else {
submit.removeAttribute('href');
}
}
</script>
A few things happened here:
The value inside a <input> is accessed by .value;
You misplaced the {
getElementById is not a global method it has to be called on the element you want to select in (in your case the document itself)
To test if two values are equal use === in js
function login() {
var password = document.getElementById("password").value;
if (password === "wima") {
document.getElementById("submit").href = "/pages/home.html";
} else {
document.getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type="text" placeholder="WIMA"><br> Password
<input id="password" type="password" placeholder="WIMA"><br>
<a class="button" id="submit" href="#" onclick="login()">
Submit
</a>
</p>

How to compare passwords in Javascript

I have a registration page and I want to compare two passwords (input fields) to be equal before writing it to a websql database.
I cannot seem to get it to work.
Any ideas?
function addTodo() {
var todo = document.getElementById("todo");
var todo2 = document.getElementById("todo2");
if(todo != todo2) {
alert("Yours passwords do not match");
} else {
curatio.webdb.addTodo(todo.value);
todo.value = "";
alert("Your Registration was successfull");
setTimeout(function () {
window.location.href = "login.html";
}, 1000);
}
}
<div data-role="fieldcontain" >
<label for="todo">
Password
</label>
<input name="" id="todo" placeholder="" value="" type="password" required>
</div>
<div data-role="fieldcontain" >
<label for="todo2">
Retype your Password
</label>
<input name="" id="todo2" placeholder="" value="" type="password" required>
</div>
You're comparing the elements instead of their values.
var todo = document.getElementById("todo");
var todo2 = document.getElementById("todo2");
if(todo != todo2) { // Oops
todo and todo2 are 2 different <input> elements.
Try using .value:
if(todo.value !== todo2.value) {
You're comparing the actual elements, which will always be true (because they are both TextFields). Compair their values, like so:
var todo = document.getElementById("todo").value;
var todo2 = document.getElementById("todo2").value;
Either this or change
if(todo != todo2)
to
if(todo.value != todo2.value)
Another way is Object.is(password, confirm_password)

Categories

Resources