How can I store localStorage value without losing last value stored on it
I write code to insert row to table contient data from input everytime I click button 'insert new row' but I have issue after fill the table I want use table's data to insert to SQL database table using localStorage and ajax I do it but my problem he give me just data of last row because when I click save he give localStorage new value
<!-- my problem : console.log shows me last item - I want to store all my inputs products without losing previous when I click button save -->
<input type="text" id="products">
<button onclick="myfunction()">save</button>
<script>
function myfunction() {
var products = document.getElementbyid("products").value;
var save_listProducts = localStorage.setItem("data",products);
}
var get_listProducts = localStorage.getItem("data");
console.log(get_listProducts);
</script>
You need to add little bit more code in order to maintain a "list" (array) in localStorage. There is no problem with actually storing an array in localStorage as long as it is a string - and to convert an array into a string ( and be able to parse it back later ) you can use JSON.stringify (and JSON.parse to get it back)
function addNewItem (item) {
let myList = JSON.parse(localStorage.getItem("myList", "[]"));
myList.push(item);
localStorage.setItem("myList", JSON.stringify(myList));
}
function getAllItems () {
return JSON.parse(localStorage.getItem("myList", "[]"));
}
function removeItem (index) {
let myList = JSON.parse(localStorage.getItem("myList", "[]"));
myList.splice(index, 1);
localStorage.setItem("myList", JSON.stringify(myList));
}
👆 This is just an example and would need to be modified to fit your code, please do not just copy/paste it
In your example
<input type="text" id="product">
<button onclick="myfunction()">save</button>
<script>
function myfunction() {
var product = document.getElementbyid("product").value;
addNewItem(product);
console.log(getAllItems());
}
function addNewItem (item) {
var myList = JSON.parse(localStorage.getItem("myList", "[]"));
myList.push(item);
localStorage.setItem("myList", JSON.stringify(myList));
}
function getAllItems () {
return JSON.parse(localStorage.getItem("myList", "[]"));
}
</script>
Related
Basically i'm wanting to capture a user's shopping basket and then print this information on a separate page. The user would be able to click on a button on the basket page which would take them to the new page (Which would have an invoice like structure showcasing their items, costs etc). Currently i have the following script running on the basket page.
jQuery( document ).ready(function($) {
var itemName = document.getElementById('itemName');
if(typeof(Storage)!=="undefined")
{
var me = {name: itemName.textContent};
localStorage.setItem("user",JSON.stringify(me));
}
else
{
// Sorry! No Web Storage support..
}
});
Which is accessing the following bit of html on the cart page
<!--START: itemnamelink--><a id="itemName" href="product.asp?itemid=[ITEM_CATALOGID]">[ITEM_NAME]</a><!--END: itemnamelink-->
On the new page i'm creating where i want the information to be displayed in an invoice like fashion i have the following code.
<script>
jQuery( document ).ready(function($) {
console.log(localStorage.getItem("user"));
var items = JSON.parse(localStorage.getItem("user"));
for(var key in items){
if(items.hasOwnProperty(key)){
document.getElementById("add").innerHTML += "name:" + "<br>" + items[key];
}
}
});
</script>
<div id="add">
</div>
However i'm getting the following being printed which is not ideal. I eventually want a few more elements being printed. I think my problem is i'm printing the whole of the local storage so in my head it's just dumping it all on one line and i need to iterate through the storage and print each element separately.
name:
red chair black chair
You need to use JSON.parse() to the objects you get from the storage.
var json = '{"name":"black chair red chair"}';
obj = JSON.parse(json);
document.getElementById('element').innerHTML = obj.name;
<div id='element'></div>
function writeToLocalStorage(obj) {
return localStorage.setItem("data", JSON.stringify(obj));
}
function getFromLocalStorage() {
return JSON.parse(localStorage.getItem("data"));
}
writeToLocalStorage({ id: "2", cart: "item" });
var data = getFromLocalStorage();
console.log(data.id);
Then access with data.name
Good evening all!
I am currently working with google maps api.
The google maps asks for a json format to set directions.
Everything works fine if i make my own json object, but i would like to retrieve data from input fields and store it in the json object.
Right now i can retrieve 1 value from the input field and store it. But i woud like to retrieve multiple values. This is needed to set an direction on the maps. I need to find a way to store the multiple values in an json object as array. Correct my if i wrote some things wrong, i am not a expert :)
"key" : "Array"
See below for the example + Code
This is what i need to try to get:
A user comes to the page and sees 2 input fields, he fills in Amsterdam and Rome but he always needs Paris. So the user press the + icon. Another input field appears and he fills in Paris. when the user submits this below must be the json result from the input fields
"locatie" : ["Berlin", "Amsterdam", "Paris", "Rome"]
This is is my form:
<form onsubmit="return make_json(this);">
Locatie: <input type="text" name="locatie">
<input type="submit" name="" value="Make Trip">
</form>
My js function:
function make_json(form) {
var json = {
"locatie" : form.locatie.value
// this is what works and what i would like to retrieve from multiple input fields
//"locatie" : ["Paris", "Amsterdam"]
};
return json;
}
In the google maps api i call the function and use the json:
var jsonArray = make_json();
You can declare an array and push the values to it when the button is clicked.
// Declare location array
var locations = [];
// Button bindings
var locationButton = document.getElementById("addNewLocation");
locationButton.onclick = addNewLocation;
var displayJsonButton = document.getElementById("displayJsonObject");
displayJsonButton.onclick = displayJsonObject;
// Button functions
function addNewLocation() {
var location = document.getElementById("locationText").value;
locations.push(location);
document.getElementById("locationText").value = "";
}
function makeJsonObject() {
var json = {
location : locations
}
return json;
}
function displayJsonObject() {
var obj = makeJsonObject();
console.log(obj.location);
}
<input id="locationText" type="text" />
<button id="addNewLocation">Add</button>
<button id="displayJsonObject">Display JSON</button>
The results will be populated in the console. I have also returned the JSON object for you in the displayJsonObject() function, which you could use to pass to the API.
You can also try this, if you want to keep showing the locations entered before adding new location.
function addInput() {
var input = document.createElement('input');
input.setAttribute("type", "text");
input.setAttribute("name", "locatie[]");
inputs.appendChild(input);
}
function make_json() {
var form = document.querySelector("form");
var values = [];
var locations = form['locatie[]'];
if (locations.length) {
locations.forEach(function(input) {
values.push(input.value);
});
} else {
values.push(locations.value);
}
var json = {
"locatie": values
};
console.log(json);
return json;
}
<form>
Locatie:
<div id="inputs">
<input type="text" name="locatie[]">
</div>
<button onClick="addInput()">+</button>
<input type="submit" value="Make Trip" onClick="make_json(this)">
</form>
Note: Take care of UI. If user enters more number of inputs, UI may deform.
I'm having hard time on this localstorage array. I have search it here but can't get it out. Hope you can help me with this one.
Here is my code.
$(function(){
var addWishlist = $('.add-wishlist');
addWishlist.click(function(e){
e.preventDefault();
var product_ids = [];
localStorage.setItem('product_ids', $(this).prev().val() );
console.log( localStorage.getItem('product_ids') );
});
});
The output is:
The output should be [2, 3, 4, 1]
You need to add it to array on button click and then store it to local storage. Also product_ids should be initialized outside the click event
var product_ids = [];
addWishlist.click(function(e){
e.preventDefault();
product_ids.push($(this).prev().val())
localStorage.setItem('product_ids',product_ids );
console.log(localStorage.getItem('product_ids') );
});
There a couple of things wrong:
The array product_ids is always empty because you need to push() or unshift(), or anything to fill the array.
localStorage can only take strings, I don't even think it will even recognize your empty array.
Changes
Added an extra button to load the data into localStorage
Text is entered then click the Add button.
The value of the text input is push()ed into the array productList.
Each time productList is updated, it is stored in a hidden input #cache
When the Done button is clicked, the value of #cache is converted into a string by JSON.stringify.
Once productList is a string, it is then stored in localStorageand is displayed in #output.
Due to SO sandbox, the Snippet doesn't work, so review this PLUNKER instead.
SNIPPET
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<fieldset>
<legend>wishList</legend>
<input id='in1'>
<button><a href='#' id='add'>Add</a>
</button>
<button><a href='#' id='done'>Done</a>
</button>
<label for='out1'>wishList:</label>
<output id='out1'></output>
<input id='cache' type='hidden'>
</fieldset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
var productList = [];
$('#add').on('click', function(e) {
e.preventDefault();
var productItem = $('#in1').val();
productList.push(productItem);
$('#cache').val(productList);
});
$('#done').on('click', function(e) {
e.preventDefault();
var cached = $('#cache').val();
var str = JSON.stringify(cached);
localStorage.setItem('proList', str);
var stored = localStorage.getItem('proList');
console.log(stored)
$('#out1').html(stored);
});
});
</script>
</body>
</html>
I'm working on a webpage where i'm trying to display a question, and have viewers submit an answer, which appears on another page. Currently, only the most recent answer is shown on the answer page. I'm not sure how to write my function so that it stores and displays all responses. (I'm new to javascript) Thanks!
<div id=q2 class="question gr">
What is good design?
<input id="q2input" type="text" >
<div class="buttons"> <button onclick="functionTwo()"
class="sbuttons">Submit</button>
<!-- View Answers Button -->
<button id="ViewAnswers2" class="vabuttons" >View Answers</button>
<script type="text/javascript">
document.getElementById("ViewAnswers2").onclick = function () {
location.href = "WhatIsGoodDesign.html";
};
</script>
</div>
<script>
function functionTwo(){
var input = document.getElementById("q2input").value;
console.log(input);
localStorage.setItem("question2", input);
window.location.href = "WhatIsGoodDesign.html";
}
</script>
Use an array instead. Currently, all you are doing is overwriting the current value in the question2 answer slot every time. Arrays are ways to store multiple data values into one variable
function functionTwo() {
var input = document.getElementById("q2input").value;
var answers = JSON.parse(localStorage.getItem("question2answers")) || [];
//Not too sure about the || [];
answers.push(input);
localStorage.setItem("question2answers", JSON.stringify(answers));
window.location.href = "WhatIsGoodDesign.html";
}
You cannot directly put an array into LocalStorage, so you have to pass it in and out as a JSON object. JSON.stringify() will turn it into a string that you can pass into LocalStorage, while JSON.parse() will translate that string back into an array.
You currently overwrite the key question2 with the new answer each time. If you want a list of the the last answers. You would have to do something along the lines of:
function functionTwo(){
var input = document.getElementById("q2input").value;
var numAnswers = localStorage.getItem("question2numAnswers") || 0;
localStorage.setItem("question2answer" + numAnswers.toString(), input);
localStorage.setItem("question2numAnswers", numAnswers + 1);
window.location.href = "WhatIsGoodDesign.html";
}
This way you keep track of the number of answers with question2numAnswers and each answer with question2answer# and you can loop through the answers on your next page by going from 0 to question2numAnswers that you store.
I have an HTML code with a select tag where the options are dynamically populated. Once the onchange event occurs the option selected gets disabled. And also if any page navigation happens the options populated previously are retrieved.
In my case once options are populated and any option is selected gets disabled( intention to not allow the user to select it again). So there might be a case where out of 3 options only two are selected and disabled so once I refresh and the options not selected previously should be enabled. And the options selected previously should be disabled. But my code enables all the options after refresh. How can I fix this?
html code
<select id="convoy_list" id="list" onchange="fnSelected(this)">
<option>Values</option>
</select>
js code
//This function says what happnes on option change
function fnSelected(selctdOption){
var vehId=selctdOption.options[selctdOption.selectedIndex].disabled=true;
localStorage.setItem("vehId",vehId);
//some code and further process
}
//this function says the process on the drop-down list --on how data is populated
function test(){
$.ajax({
//some requests and data sent
//get the response back
success:function(responsedata){
for(i=0;i<responsedata.data;i++):
{
var unitID=//some value from the ajax response
if(somecondition)
{
var select=$(#convoy_list);
$('<option>').text(unitID).appendTo(select);
var conArr=[];
conArr=unitID;
test=JSON.stringify(conArr);
localStorage.setItem("test"+i,test);
}
}
}
});
}
//In the display function--on refresh how the stored are retrievd.
function display(){
for(var i=0;i<localStorage.length;i++){
var listId=$.parseJSON(localStorage.getItem("test"+i)));
var select=$(#list);
$('<option>').text(listId).appendTo(select);
}
}
In the display function the previously populated values for the drop down are retrieved but the options which were selected are not disabled. Instead all the options are enabled.
I tried the following in display function
if(localStorage.getItem("vehId")==true){
var select=$(#list);
$('<option>').text(listId).attr("disabled",true).appendTo(select);
}
But this does not work.
Elements on your page shouldn't have same ids
<select id="convoy_list" onchange="fnSelected(this)">
<option>Values</option>
</select>
In your fnSelected() function you always store item {"vehId" : true} no matter what item is selected. Instead, you should for example first assign some Id to each <option\> and then save the state only for them.
For example:
function test(){
$.ajax({
//some requests and data sent
//get the response back
success:function(responsedata){
for(i=0;i<responsedata.data;i++):
{
var unitID=//some value from the ajax response
if(somecondition)
{
var select=$("#convoy_list"); \\don't forget quotes with selectors.
var itemId = "test" + i;
$('<option>').text(unitID).attr("id", itemId) \\we have set id for option
.appendTo(select);
var conArr=[];
conArr=unitID;
test=JSON.stringify(conArr);
localStorage.setItem(itemId,test);
}
}
}
});
}
Now we can use that id in fnSelected():
function fnSelected(options) {
var selected = $(options).children(":selected");
selected.prop("disabled","disabled");
localStorage.setItem(selected.attr("id") + "disabled", true);
}
And now in display():
function display(){
for(var i=0;i<localStorage.length;i++){
var listId = $.parseJSON(localStorage.getItem("test"+i)));
var select = $("convoy_list");
var option = $('<option>').text(listId).id(listId);
.appendTo(select);
if(localStorage.getItem(listId + "disabled") == "true"){
option.prop("disabled","disabled");
}
option.appendTo(select);
}
}
Also maybe not intended you used following shortcut in your fnSelected:
var a = b = val;
which is the same as b = val; var a = b;
So your fnSelected() function was equivalent to
function fnSelected(selctdOption){
selctdOption.options[selctdOption.selectedIndex].disabled=true;
var vehId = selctdOption.options[selctdOption.selectedIndex].disabled;
localStorage.setItem("vehId",vehId); \\ and "vehId" is just a string, always the same.
}
Beware of some errors, I didn't test all of this, but hope logic is understood.