How to stop overwriting object values - javascript

I create a function in which my input values of form are being collected in an object then afterwards I push whole object in an array and save my array in local Storage...But the problem is when I change the value and sign up again my old values are overwritten with new one but I want it to push on index 1 of array so that my array contain 2 objects and so on... Please help me Thanking You.
<script>
var labelsarray = document.getElementsByTagName("label");
var inputsarray = document.getElementsByTagName("input");
var array = [];
function subm() {
var users = {
FirstName: inputsarray[0].value,
LastName: inputsarray[1].value,
UserName: inputsarray[2].value,
Password:  inputsarray[3].value,
DateofBirth: inputsarray[4].value,
Age: inputsarray[5].value,
Purpose: ""
};
if (inputsarray[6].checked === true) {
users.Gender = "Male";
}
else if (inputsarray[7].checked === true) {
users.Gender = "Female";
}
if (inputsarray[8].checked === true) {
users.Purpose += " Storing Apps";
}
if (inputsarray[9].checked === true) {
users.Purpose += " Storing Sites";
}
if (inputsarray[10].checked === true) {
users.Purpose += " Fun";
}
array.push(users);
for (var i=0;i<array.length;i++) {
localStorage.setItem("User Data: ", JSON.stringify(array[i]));
}
}
</script>
<div>
<center>
<form action="Javascript:void(0);"method="post" onsubmit="subm();">
<label for="fname">First Name:</label> 
<input type="text" id="fname" />
<br/>
<label for="lname">Last Name:</label> 
<input type="text" id="lname" />
<br/>
<label for="uname">User Name:</label> 
<input type="text" id="uname" />
<br/>
<label for="pass">Password:</label>  
<input type="text" id="pass" />
<br/>
<label for="dob">Date of Birth:</label>  
<input type="date" id="dob" />
<br/>
<label>Age:</label>     
<input type="text" id="age" />
<br/>
<span>Gender:</span>     
<input type="radio" name="gender" id="male" />
<label for="male">Male</label>
<input type="radio" name="gender" id="female" />
<label for="female">Female</label>
<br/>
<p>For what purpose(s) you are making account?</p>
<input type="checkbox" id="app" name="purpose" value="storingapps" />
<label for="app">Storing Apps</label>
<input type="checkbox" id="site" name="purpose" value="storingsites" />
<label for="site">Storing Sites</label>
<input type="checkbox" id="fun" name="purpose" value="fun" />
<label for="fun">Fun</label>
<br/>
<input type="submit" value="Submit" class="button" />
</form>
</center>
</div>

Each time you save in your local storage you are saving just the last item. Because each save will be replaced by the next one and only the last one would be visible. Instead you only need to save the array into the local storage
// (not needed) for (var i=0;i<array.length;i++) {
localStorage.setItem("User Data: ", JSON.stringify(array));
// (not needed) }
Now your local storage will have array of objects

You're recreating your array every time instead of reading it from Local Storage. As such, you're starting with a fresh array every time.
Where you're doing var array = []; you should be reading from local storage.
For example:
var array = [];
var savedArrayJSON = localStorage.getItem("userData");
if (savedArray) {
try {
array = JSON.parse(savedArrayJSON);
} catch (e) {
// Probably do nothing
}
}
...
array.push(users);
// No more for-loop
localStorage.setItem("userData", JSON.stringify(array));

After you set up your array, you loop through it and upon each iteration you are overwriting the User Data key from the last iteration in localStorage, so only the last array item is getting stored:
for (var i=0;i<array.length;i++) {
localStorage.setItem("User Data: ", JSON.stringify(array[i]));
}
You should just set the entire array into local storage or make distinct keys to store the individual items with:
localStorage.setItem("User Data: ", JSON.stringify(array));
Next, each time someone comes to your page, you create a new, empty array, so when does the data in localStorage ever get pulled out and used? Upon page access, you should be getting the saved data so that you can push more into it:
// Set the array variable equal to the array in localStorage or an empty array
var array = JSON.parse(localStorage.getItem("User Data")) || [];
ADDITIONAL NOTES:
Your HTML is not valid and follows out of date methodologies.
Javascript:void(0);
Is not only mis-capitalized (should be: javascript:void()), but that entire technique for doing nothing shouldn't be used as well as onsubmit (HTML event handling attributes). All your JavaScript should be in dedicated scripts and event handling should be done using element.addEventListener().
<center> is deprecated. All formatting should be done with CSS.
<input> and <br> elements should not use the XML self-terminating syntax of /> at the end of the tag. While this is legal, it is a left-over relic of 2000 when the world thought that XML was going to be the future. It buys you nothing in your code and can lead to bugs when not used correctly.

You can try the following code.This occurs because you are overwriting the localStorage values everytime you are creating a new user.A simple solution is to store the users in array format and appending new users to it everytime a new user fill up form and then save it to the localStorage.
```
<script>
var labelsarray = document.getElementsByTagName("label");
var inputsarray = document.getElementsByTagName("input");
//Here We first Grab the already stored value from the localStorage and parse it because it is in string format.
var array = JSON.parse(localStorage.getItem('User Data: ')) || [];
function subm() {
var users = {
FirstName: inputsarray[0].value,
LastName: inputsarray[1].value,
UserName: inputsarray[2].value,
Password:  inputsarray[3].value,
DateofBirth: inputsarray[4].value,
Age: inputsarray[5].value,
Purpose: ""
};
if (inputsarray[6].checked === true) {
users.Gender = "Male";
}
else if (inputsarray[7].checked === true) {
users.Gender = "Female";
}
if (inputsarray[8].checked === true) {
users.Purpose += " Storing Apps";
}
if (inputsarray[9].checked === true) {
users.Purpose += " Storing Sites";
}
if (inputsarray[10].checked === true) {
users.Purpose += " Fun";
}
//We Now append the users to the array and save it to localStorage.
array.push(users);
localStorage.setItem("User Data: ", JSON.stringify(array));
}
```
I hope this works for you also.

Related

Appending Value to LocalStorage

I want to add new values to localStorage for my Pizza website in which I want the admin to be able to add pizzas. I have this code:
function store() {
var inputName = document.getElementById("name");
localStorage.setItem("name", inputName.value);
var inputDescription = document.getElementById("description");
localStorage.setItem("description", inputDescription.value);
var inputPrice = document.getElementById("price");
localStorage.setItem("price", inputPrice.value);
}
<form onsubmit="store()" id="form1">
<label for="name">Namn:</label><br>
<input class="name" type="text" id="name" name="name" placeholder="Skriv här..."><br>
<label for="description">Beskrivning:</label><br>
<input class="description" type="text" id="description" name="description" placeholder="Skriv här...">
<br>
<label for="price">Pris:</label><br>
<input class="margin-bot" type="text" id="price" name="price" placeholder="Skriv här...">
<br>
<br>
<button form="form1" class="submit-button" type="submit">Lägg Till</button>
</form>
How do I add new pizzas for each time? Everytime I try to add a new value it just replaces the existing one.
function store() {
let inputName = document.getElementById("name");
let inputDescription = document.getElementById("description");
let inputPrice = document.getElementById("price");
let pizzas = []
if(localStorage.getItem("pizzas")){
pizzas = JSON.parse(localStorage.getItem("pizzas"));
}
let pizza = {}
pizza.name = inputName.value;
pizza.description = inputDescription.value;
pizza.price = inputPrice.value;
pizzas.push(pizza)
localStorage.setItem("pizzas", JSON.stringify(pizzas))
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form onsubmit="store()" id="form1">
<label for="name">Namn:</label><br>
<input class="name" type="text" id="name" name="name" placeholder="Skriv här..."><br>
<label for="description">Beskrivning:</label><br>
<input class="description" type="text" id="description" name="description" placeholder="Skriv här...">
<br>
<label for="price">Pris:</label><br>
<input class="margin-bot" type="text" id="price" name="price" placeholder="Skriv här...">
<br>
<br>
<button form="form1" class="submit-button" type="submit">Lägg Till</button>
</form>
</body>
</html>
This should help, first I check the localStorage some pizza is already stored in there or not, if there, then I take that parse it and add one more pizza to it from the form input, if not I create a completely new array and then add the value from the form input then store it in the localStorage.
first it would be better to replace your code to use "objects & arrays" instead of "string variables", like this example i made for you:
function store() {
var inputName = document.getElementById("name");
var inputDescription = document.getElementById("description");
var inputPrice = document.getElementById("price");
return ({
name: inputName.value,
description: inputDescription.value,
price: inputPrice.value
});
}
function updateStore(key = 'pizzas'){
let pizzasArray = JSON.parse(localStorage.get(key)) || [];
pizzasArray.push(store());
localStorage.setItem(key, JSON.stringify(pizzasArray));
}
You can keep it as json array in local storage.For Example;
function addStoreForArray(key, value) {
var storeArrayObj = localStorage.getItem(key);
if(storeArrayObj){
storeArrayObj = JSON.parse(storeArrayObj);
storeArrayObj.push(value);
} else {
storeArrayObj = [];
storeArrayObj.push(value);
}
localStorage.setItem(key, JSON.stringify(storeArrayObj));
}
addStoreForArray('pizzas', {name:'pizzaName', description: 'pizzaDescription', price: 10});
You can create an array to store many pizzas and to check if already exists you can call the getStorage() function and if storagePizzas includes your new pizza then update the value
arrayOfPizzas = []
function storeArray() {
let pizzaCreated = {}
pizzaCreated.name = document.getElementById("name").value;
pizzaCreated.description = document.getElementById("description").value;
pizzaCreated.price = document.getElementById("price").value;
let storageItems = getStorage();
// Check ...
arrayOfPizzas.push(pizzaCreated);
setStorage(arrayOfPizzas);
}
function setStorage(arr){
localStorage.setItem('arrayOfPizzas', JSON.stringify(arr));
}
function getStorage(){
return JSON.parse(localStorage.getItem('arrayOfPizzas');
}
You need to store the pizzas the user has created in an array. You can store the array in local storage, you just need to make sure you can serialize and deserialize it properly
Take the values from the input field
Grab your array of pizzas from local storage
If the array doesn't exist yet, getItem will return null, so you can give it an array to start off with.
Add the new pizza to the array
Save the pizzas array in local storage again.
function store() {
var newPizza = {
name: inputName.value,
description: inputDescription.value,
price: inputPrice.value
}
var pizzas = localStorage.getItem('pizzas')
if (!pizzas) {
pizzas = []
} else {
pizzas = JSON.parse(pizzas)
}
pizzas.push(newPizza)
localStorage.setItem('pizzas', JSON.stringify(pizzas))
}

How to store inputs multiple times into local storage

I am currently inputting values into local storage like this
<form name="myform" action="" method="GET">
Event Name: <INPUT TYPE="text" NAME="name" VALUE="" id="input1"><br />
Event Date and Time: <INPUT TYPE="datetime-local" NAME="date" Value="" id="input2"><br />
Event Location: <INPUT TYPE="text" NAME="location" VALUE="" id="input3"><br />
Event Notes: <INPUT TYPE="text" NAME="notes" VALUE="" id="input4"><br />
<button onclick="storeValues(event)" type=submit>Submit</button>
</form>
<script>
function storeValues(e) {
e.preventDefault();
let storedEvents = JSON.parse(localStorage.getItem("Events")) || [];
const newEventDetails = {
name: document.getElementById('input1').value,
dateTime: document.getElementById('input2').value,
location: document.getElementById('input3').value,
notes: document.getElementById('input4').value
}
storedEvents.push(newEventDetails);
localStorage.setItem("Events", JSON.stringify(storedEvents));
console.log('storedEvents', storedEvents);
}
</script>
However I found that I was unable to Output more than 1 value from local storage which I am currently achieving doing this.
<h2 class="title">Upcoming Events</h2>
<h3 id='input1'> </h3>
<h3 id='input2'> </h3>
<h3 id='input3'> </h3>
<h3 id='input4'> </h3>
<!-- running script here will populate H2's with values from local storage -->
<script>
document.getElementById('input1').innerText = localStorage.getItem('EventName');
document.getElementById('input2').innerText = localStorage.getItem("EventDateAndTime");
document.getElementById('input3').innerText = localStorage.getItem("EventLocation");
document.getElementById('input4').innerText = localStorage.getItem("EventNotes");
</script>
How would I be able to display the most recent input using those fields and then display ALL previous inputs on another page?
Your current code won't work, because you're retrieving items from EventName, EventDateAndTime, etc properties of local storage, but you never save to those properties, so they'll be null.
You're storing all the event info in a single property, localStorage.Events, which contains an array that you push to when you add a new event. So, to display the last item saved, you just need to access the top item in the array, and to display previous items saved, just access the appropriate previous index in the array:
const renderEvent = (event) => {
document.getElementById('input1').textContent = event.name;
document.getElementById('input2').textContent = event.dateTime;
document.getElementById('input3').textContent = event.location;
document.getElementById('input4').textContent = event.notes;
};
// Display last event:
const storedEvents = JSON.parse(localStorage.getItem("Events"));
if (!storedEvents) throw new Error('No events');
const lastEvent = storedEvents.pop();
renderEvent(lastEvent);
// Display nth event:
const index = 5; // for example: display 5th event saved
const storedEvents = JSON.parse(localStorage.getItem("Events"));
if (!storedEvents) throw new Error('No events');
const event = storedEvents[index];
renderEvent(event);

Compare input text with person name belongs to only one input number id

Im trying to write a validation for 2 groups of fields. I have 6 inputs, 3 for text name and 3 more for id number... the validation should do this "if input name="RE_SignedByID" has an input type name="RE_SignedByName", then other inputs name="RE_SignedByID", should NOT contain the same name="RE_SignedByName" More easy explanation... one ID number should have only one Person Name (Id number is unique for one person name). What can I use for that? Should I map() all the inputs?
Those are my inputs:
<div id="signedBy" class="clearfix">
<label>Signer, person ID & name</label>
<span id="signedByID" class="ids half">
<input type="text" name="RE_SignedByID" placeholder="personID, person1" data-validate="" tabindex="101" required>
<input type="text" name="RE_SignedByID" placeholder="personID, person2" data-validate="" tabindex="103">
<input type="text" name="RE_SignedByID" placeholder="personID, person3" data-validate="" tabindex="105">
</span>
<span class="names half">
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" required>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="104">
<input type="text" name="RE_SignedByName" placeholder="name, person3" tabindex="106">
</span>
</div>
I guess it should also be an "on change" function? or can I make the validation on click? Some ideas...? Im actually compleatley lost here...
Thanks in advance!!!
Maybe use different class names for all 3 of them to make them unique?
<input class="name1">
<input class="name2">
<input class="name3">
I'm not sure what you mean but if you want to make the input types unique and not call them all when you write class="names half", then you should give them all unique class names.
So from my understanding you don't want multiple fields to have the same value.
My approach would be this:
let inputTimeout = null; //set an empty timeout object
let vars = [null, null, null, null]; // create an array containing as many nulls as you have inputs
$('.nameInput').on('keyup', function(){
let self = $(this);
clearTimeout(inputTimeout); //clear the timeout
inputTimeout = setTimeout(function(){ //set a timeout to check whether there is a dupe after the user has stopped typing
if (vars.indexOf(self.val()) == -1){ //check if the vals array contains the newly entered string
vars[self.attr('data-inputnum')] = self.val(); //insert the value into the array
}else{
//handle duplicates here
}
}, 500); //500ms is a sensible value for end of user input, change it if users complain that your app is too fast/slow
});
You then just have to edit your HTML a bit so that all name inputs have a class in common (i used .nameInput) and have a data-inputnum attr.
This would look something like this:
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" class='nameInput' data-whichinput='0'/>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="103" class='nameInput' data-whichinput='1'/>
<!--and so on-->
Of course, never rely on JavaScript verification alone, always also check inside your backend. However this would be out of scope for this answer.
Hi Thanks all for the help, made me realize a couple of things till I got the answer. This is my working code:
var valSignedID = $("[name=SignedByID]").map(function() {
return this.value.trim();
}).get();
var valOwnersID = $("[name=OwnersID]").map(function() {
return this.value.trim();
}).get();
valSignedID.sort();
valOwnersID.sort();
for (var i = 0; i < valSignedID.length - 1; i++) {
if (valSignedID[i] == valSignedID[i + 1] && valSignedID[i] != "") {
alert(" You can not have duplicated signers ID's");
return false;
// break;
}
}
for (var i = 0; i < valSingedName.length; i++) {
if (valSingedName[i] == valSingedName[i + 1] && valSingedName[i] != "") {
alert(valSingedName[i] + " should not have different ID");
//return false;
}
}

how to convert variable name into index string of object jquery

when I make a looping based on the content in the form of an input form
I'll take the attribute name to be used as a selector element and object index array of data, but the index is the variable name
how to convert from a variable name to string index on an object array
of data?
it aims to make input in the form can be filled automatically from the object array of data
var data = {
id: "4",
Model: "804",
Description: "AXIAL SETTER,100MM, MAGNETIC BASE"
};
var names = [];
if ($('#form').length == 1) {
$('#form :input').each(function() {
names.push($(this).attr('name'));
});
$.each(names, function(key, value) {
$('[name="' + value + '"]').val(data.value);
//value should be change with name,
//for example :
// $('name="Description"').val(data.Description);
});
}
<form action="#" id="form" class="form-horizontal">
<input type="hidden" name="id" />
<br/>
<input type="text" name="Model" placeholder="Model Of product" />
<br/>
<input type="text" name="Description" placeholder="Description Of product" />
<br/>
<button type="submit" class="btn-save">save</button>
</form>
No need to run twice over the same data. You could simply do this to fill your form:
var data = {
id: "4",
Model: "804",
Description: "AXIAL SETTER,100MM, MAGNETIC BASE"
};
if ($('#form').length == 1) {
$('#form :input').each(function() {
if (typeof data[$(this).attr('name')] != 'undefined'){
$(this).val(data[$(this).attr('name')]);
}
});
}
Have a look at https://jsfiddle.net/nfq22d9r/1/
The code runs through all the forms input fields, checks if a fields name is existent as a key in the data object and sets the fields value to the one in the data object, if the key was found

Build and manipulate array based on required fields populated

I'm trying to figure out a sensible way to display and manipulate an array/list of required fields which are yet to be populated in a form - this is just so i can output this info to the user and remove each item from the list as the user goes through and populates the fields (as a sort of progress indicator). Any thoughts on how best to handle this?
I'm thinking of something along the lines of the following:
var reqFields = [];
jQuery('label.required').each(function() {
console.log(jQuery(this).text());
reqFields.push(jQuery(this).text());
});
jQuery('.custom-field').on('input', function() {
if (jQuery('.required-entry').filter(function() {
return this.value.length === 0;
}).length === 0) {
// Remove this from the list/array
} else {
}
});
On input event check the value and accordingly add/remove item in array.
var reqFields = [];
jQuery('label.required').each(function() {
console.log(jQuery(this).text());
reqFields.push(jQuery(this).text());
});
jQuery('.custom-field').on('input', function() {
if (this.value) {
// Remove this from the list/array
reqFields.splice(jQuery(this).index(),1);
// jQuery(this).index() havent tried, else just compute index some other way
} else {
// add back if cleared out
reqFields.push( jQuery('label.required').eq(jQuery(this).index()).text());
}
});
Instead of removing the entries, every time there's a change in input of the required fields, you can simply re-assign the reqFields array to the list of required fields with empty input.
var reqFields = [];
jQuery(function() {
jQuery('.requiredFields').on('input', function() {
reqFields = jQuery('.requiredFields').filter(function() {
return this.value.length === 0;
});
});
});
Check this basic example bellow using each on input to loop through all the fields with class required-entry and check the empty ones to finally append message to span #msg to inform the user which fields are required.
Hope this helps.
$('.required-entry').on('input', function() {
$('#msg').empty();
$('.required-entry').each(function() {
if ( $(this).val().length == 0 )
$('#msg').append('Field <b>'+$(this).prev('label').text()+'</b> is required.<br/>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class='required'>First Name</label>
<input type='text' id='first_name' name='first_name' class='required-entry' required/>
<br/>
<label class='required'>Last Name</label>
<input type='text' id='last_name' name='last_name' class='required-entry' required/>
<br/>
<label class='required'>Email Address</label>
<input type='text' id='email' name='email' class='required-entry' required/>
<hr/>
<br/>
<span id='msg'></span>

Categories

Resources