i got some saved variables using localstorage, what i want to do is to put them into textfields automatically each time the page loads
<script language="javascript">
function save() {
var value1 = document.getElementById("email").value;
var value2 = document.getElementById("password").value;
localStorage.setItem("eaddress", value1);
localStorage.setItem("pwd", value2);
}
</script>
i've got some textfields on the page namely email and password
If you want to do this with jQuery, this should accomplish what you're trying to do. Please note that I couldn't get the demo running in the snippet below because Stack Overflow is preventing form submissions.
$(function() {
var
$email = $('#email'),
$password = $('#password'),
emailValue = localStorage.getItem("eaddress"),
passwordValue = localStorage.getItem("pwd");
// SAVE VARIABLES TO LOCAL STORAGE
$('form').on('submit', function() {
localStorage.setItem("eaddress", $email.val());
localStorage.setItem("pwd", $password.val());
});
// IF EMAIL AND PASSWORD ARE SAVED, PREPOPULATE THE FORM FIELDS
if (emailValue != null) {
$email.val(emailValue);
}
if (passwordValue != null) {
$password.val(passwordValue);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="email" id="email" />
<input type="password" id="password" />
<button type="submit">Submit</button>
</form>
Related
I have recently started learning Python and jQuery. I am doing a small exercise for validating the form from back-end. I do not want to submit the form if the validation fails.
Here, I want to print the message, user already exists if user record is present in the backend. The code I wrote for validation works but by form is always getting submitted. Much appreciate guidance from this forum on how to handle this form submission.
Here's a snippet of my code:
HTML:
<form action="/register" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="username" id="user" placeholder="Username*" type="text" required>
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password*" type="password" required>
</div>
$('form').on('submit', function(e) {
let user = document.querySelector("#user").value;
$.get('/validate?q=' + user, function(users) {
let text = '';
if (users.length != 0) {
document.querySelector("#error").innerHTML = "Username already exists";
return false;
}
});
});
application.py
#app.route("/validate")
def validate():
user = request.args.get("q")
row = db.execute("SELECT username FROM users WHERE username = ?", user)
print(row)
return jsonify(row)
You need to validate that outside your "get" function, preferably using a variable.
$('form').on('submit', function(e) {
var chkUser = 0;
let user = document.querySelector("#user").value;
$.get('/validate?q=' + user, function(users) {
let text = '';
chkUser = users.length;
if (users.length != 0) {
document.querySelector("#error").innerHTML = "Username already exists";
return false;
}
});
if (chkUser > 0)
return false;
});
I haven't tested this code. Also you should mention how are you subtmitting your form. The easiest way is just to have an <input type='submit'> element.
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);
I've been trying to compare two inputs.
First input is type "hidden" and get value from database.
For second input - value insert customer, but only if is same as in database, can her update his data.
Here is php:
<input id="pass1" type="hidden" value= "'.$row_pswd['pswd'].'" />
<input id="pass2" type="password" placeholder="password" required />
and script:
<script>
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").<?php echo SHA1("value"."t&#sdhstöksdf54gh"); ?>;
var ok = true;
if (pass1 != pass2) {
alert("Passwords Do not match");
document.getElementById("pass2").style.borderColor = "#E34234";
ok = false;
}
else {
alert("Passwords Match!!!");
}
return ok;
}
</script>
Any help would be much appreciated.
I don`t think its a good idea to do that in Javascript. You kinda giving the way user password this way. Also hidden field with the password as value? Not good!
Move all this into php. Make the person first write the password, compare it in php and than update the info. If you want to do it in one page, use ajax.
The function receives the username and password of the user. If either are left empty, nothing happens and they won't be linked to google.ca if they click the "Go" button. If they filed in the required sections then they will be directed to google.ca. For some reason, if any of the text boxes are left unfilled and the Go button is pressed, it brings me to a 404 error page when I want it to just stay on that page until the user fills the textbox. What is causing this problem? This is the HTML file.
<form action="index.php" method="get" id="form" onsubmit="return go(document.getElementById('username'), document.getElementById('password'))">
<table>
<tr><td>Username: <input type="text" name="username" maxlength="16" id="username" onKeyUp="updateLength('username', 'usernameLength')" onblur="checkTextField(this);"/> <span id="usernameLength"></span></td></tr>
<tr><td>Password: <input type="password" name="password" maxlength="50" id="password" onKeyUp="updateLength('password', 'passwordLength')"> <span id="passwordLength" onblur="checkTextField(this);"></span></td></tr>
<tr><td><input type="submit" value="Go" id="goButton" onclick="go(username, password)"/></td></tr>
</table>
</form>
And here is the js file
function loginFunction() {
var url = "login.html";
window.open(url);
}
function createAccountFunction() {
var url2 = "createAccount.html";
window.open(url2);
}
function go(username, password) {
if (username != null && password != null) {
var url = "https://www.google.ca/";
window.open(url);
}
}
function updateLength(field, output) {
var curr_length = document.getElementById(field).value.length;
var field_mLen = document.getElementById(field).maxLength;
document.getElementById(output).innerHTML = curr_length + '/' + field_mLen;
}
function checkTextField(field) {
if (field.value == '')
alert("Field is empty");
}
You aren't stopping the default event of the onsubmit. You can do that by changing your go function to:
function go(username, password) {
return function(event) {
event.preventDefault();
if (username != null && password != null) {
var url = "https://www.google.ca/";
window.open(url);
}
}
}
You also don't need the return in the HTML. Just call the function.
I didn't understand your code logic, but maybe I can offer you a way to fix your code by yourself.
You have a form and a button. If you click on the button you execute the go() function. Because the button is a submit button, on the same click you execute one more time the go() function.
My advice is to create a new function, you may name it validate():
function validate() {
var username = document.get........
var password = document.get........
// more logic here, if need
if(!username || !password) {
return false;
}
return true
}
and now, your submit button looks like:
<input type="submit" value="Go" id="goButton" onclick="return validate()"/>
The form won't submit if the validate() function returns false.
Hope this helps.
I have a form that makes logging into a website but not in mine and I want them to be saved form data in my web with HTML5 local storage. But not how. Any idea? My form is this:
<form action="http://issuefy.ca.vu/on/login.php" class="form-login" method="post" />
<input name="email" type="email" id="email" required="" placeholder="Email" />
<input name="password" type="password" required="" placeholder="Contraseña" />
</form>
LocalStorage has a setItem method. You can use it like this:
var inputEmail= document.getElementById("email");
localStorage.setItem("email", inputEmail.value);
When you want to get the value, you can do the following:
var storedValue = localStorage.getItem("email");
It is also possible to store the values on button click, like so:
<button onclick="store()" type="button">StoreEmail</button>
<script type="text/javascript">
function store(){
var inputEmail= document.getElementById("email");
localStorage.setItem("email", inputEmail.value);
}
</script>
Here's a quick function that will store the value of an <input>, <textarea> etc in local storage, and restore it on page load.
function persistInput(input)
{
var key = "input-" + input.id;
var storedValue = localStorage.getItem(key);
if (storedValue)
input.value = storedValue;
input.addEventListener('input', function ()
{
localStorage.setItem(key, input.value);
});
}
Your input element must have an id specified that is unique amongst all usages of this function. It is this id that identifies the value in local storage.
var inputElement = document.getElementById("name");
persistInput(inputElement);
Note that this method adds an event handler that is never removed. In most cases that won't be a problem, but you should consider whether it would be in your scenario.
Here,Simple solution using JQUERY is like this..
var username = $('#username').val();
var password = $('#password').val();
localStorage.setItem("username", username);
localStorage.setItem("password", password);
To save the data you have to use
localStorage.setItem method and to get the data you have to use
localStorage.getItem method.
This is my function from my CMS, that save all TEXTAREA and INPUT values on "keyup"
and place it in the right element on reload.
After the form has been submitted, only the submitted form is deleted from the local storage.
Set it to buttom of your page, thats it.
(function (mz,cms,parentKey,subKey) {
setTimeout(function() {
const storeAll = "textarea,input";
const formArray = mz.querySelectorAll(storeAll);
parentKey = window.location.href+"-";
formArray.forEach((formItem) => {
if (formItem) {
subKey = formItem.getAttribute("name");
var key = parentKey+subKey;
if (localStorage[key]) {
var _localStorage = localStorage[key] ;
formItem.value = _localStorage;
}
formItem.addEventListener("keyup", function () {
var _localStorage = formItem.value;
var T = formItem.getAttribute("type");
if (T == "password" || T == "hidden" || T == "submit" || formItem.disabled) {
//console.log("Ignore: "+formItem.getAttribute("name"));
return;
}
localStorage.setItem(key, _localStorage);
} , false);
formItem;
}
});
const submitForm = mz.querySelectorAll("form");
submitForm.forEach((submitItem) => {
if (submitItem) {
submitItem.addEventListener("submit", function (e) {
// e.preventDefault();
const formArray = submitItem.querySelectorAll("textarea,input");
formArray.forEach((formItem) => {
subKey = formItem.getAttribute("name");
localStorage.removeItem(parentKey+subKey);
} , false);
} , false);
}
});
}, 1);
}(this.document,'','',''));