How can i save form.serialize value to a variable repeatedly - javascript

Hi i have add to cart button in my site. When button is clicked then the value in the form is store to a variable . var cartData = $('form').serialize();
My requirement is when the user select select next product in the page without refreshing , the form data need to save in var cartData without losing previous data,i.e i need to save this data as array. How can i do that. when i use var cartData = $('form').serializeArray(); then the cartdata only contain new valus , not previous values of form serialize.

form data need to save in var cartData without losing previous data,i.e i need to save this data as array
So you can push serialize result to actual array. For example:
var cartData = [];
// Save first form
cartData.push($('form').serialize());
// Later next form
cartData.push($('form').serialize());
This way you can store all forms you need in one data array.

Related

How to push an object in a object - javascript

I have two ways to fill the same hidden input in a form
Using an import CSV button
Adding data using another inputs
When I use the first option, the hidden input is filled with this
for example:
correct data
[{"url":"http://www.restaurant.com","businessTypeId":"1"},{"url":"http://www.hotel.com","businessTypeId":"2"}]
and works correctly if I store this data
but when I use the second option, the input is filled with this:
incorrect data
{"url":"http://www.google.com","businessTypeId":"3"}
That's incorrect because it doesn't have [brackets] at the beginning neither at the end
Another problem is when I insert data and fill that hidden input (with the first way) and then I try to add more data using the second way,
I get this
[{"url":"http://www.restaurant.com","businessTypeId":"1"},
{"url":"http://www.hotel.com","businessTypeId":"2"}],
{"url":"http://www.google.com","businessTypeId":"3"}
the first 2 data was inserted using the first way, the third data was inserted using the 2nd way
all data should be inside those brackets []
how can I "open" the brackets to push new data and "close" them?
at the beginning of all the code, the variable starts like this
let placesArray = [];
after the first method, data is inserted using this
placesArray.push(JSON.stringify(csvResult));
document.getElementById('places').value = placesArray;
them, after the second method, data is inserted using this
placesArray.push(JSON.stringify(placeData));
console.log('placeData datatable ' + placeData);
document.getElementById('places').value = placesArray;
Note: if I use the first method two times, brackets are duplicated, like this
[{"url":"http://www.restaurant.com","businessTypeId":"1"}
{"url":"http://www.hotel.com","businessTypeId":"2"}],
[{"url":"http://www.beauty-shop.com","businessTypeId":"3"},
{"url":"http://www.dentist.com","businessTypeId":"5"}]
I definitely need to "open" the object so that I can insert the new data and not go through this, how could I do that?
In the console.log, I have this for placeData [object Object], same result for csvResult, both are object
You could flatten the array before every value set
placesArray = placesArray.flat()
document.getElementById('places').value = placesArray;
Seems like csvResult is itself an array and as you stringify it and push it to placesArray, it doesn't look like the result you want.
I'd go with this instead
placesArray.push(...csvResult) // push each `csvResult` item into `placesArray`
document.getElementById('places').value = JSON.stringify(placesArray)
SOLVED:
I erased all JSON.stringify and added it to every line when I push data into inputs
like this
document.getElementById('places').value = JSON.stringify(placesArray);
in all lines when this is used.
thanks to #hgb123
for prevent to accumulate [brackets[more brackets]] I used .flat()
placesArray = placesArray.flat()
document.getElementById('places').value = JSON.stringify(placesArray);

How to store value from local storage in an array, JavaScript?

I have been trying to code in javascript where I want input given to be displayed on screen. I want to store the data from input in LocalStorage. I tried to take the value and using localStorage.setItem and localStorage.getItem I stored in local storage too. But as I want to display all the records I have inserted every time submit button has been clicked, I want to store current and previous records too.
I tried to push into an array but it had only current records and not previously stored values. I don't want jquery. I just want simple javascript code.
thank you.
eg-
var data=[];
function myFunction(data)
{
var name= document.getElementById("nm").value;
localStorage.name= name;
for(var i=0;i<localStorage.length;i++)
{
var key = localStorage.key(i);
var value = localStorage.getItem(key);
data.push( value);
}
}
Yep, as mentioned in the comments it is best to just store the String representation of your array and store it as a value in localstorage. Web localstorage lets you store simple key value pairs which can be integers or strings (mostly strings) official docs
You could do something like this:
var name= document.getElementById("nm").value;
var data;
if (localStorage.getItem("name") === null)
//First value to be stored
data = [];
else
//There is some value already in the array
data = JSON.parse(localStorage.getItem("name"));
//Push name to data array in any case
data.push(name);
//Update localStorage
localStorage.setItem("name",JSON.stringify(data));
I hope this gets you started in the right direction.

adding list to array of list in localstorage

I have list of students like as follows form from user input form:
//student form input for 1st time
var student={name:"a",roll:"9",age:13}
//student form input for 2nd time
var student={name:"b",roll:"10",age:14}
//student form input for 3rd time
var student={name:"c",roll:"11",age:15}
Actually, i am developing phonegap applications. Each time the user submit form-input i.e. student information, I want to save them into localstorage. Finally, when online, i want to sync them. I know i can store them in localstorage as follows:
localStorage.setItem("studentinfo", JSON.Stringfy(student));
But, this will remove the first student info in the local storage when i save second student info.
Infact, when i save first, second and third input respectively, i want to add them in localstorage array and finally the result in localstorage should be like
key=studentlist,
value=[
{name:"a",roll:"9",age:13},
{name:"b",roll:"10",age:14},
{name:"c",roll:"11",age:15}
]
How can it be done in localstorage or phonegap localstorage?
You want to hold all your students in an array like this:
var students = [];
students.push({name:"a",roll:"9",age:13});
students.push({name:"b",roll:"10",age:14});
students.push({name:"c",roll:"11",age:15});
And then store that in localStorage:
localStorage.setItem('studentsInfo', JSON.stringify(students));
The best way to do that would be with a function like this:
// When you get more student information, you should:
var addNewStudent = function (name, roll, age) {
// retrieve it (Or create a blank array if there isn't any info saved yet),
var students = JSON.parse(localStorage.getItem('studentsInfo')) || [];
// add to it,
students.push({name: name, roll: roll, age: age});
// then put it back.
localStorage.setItem('studentsInfo', JSON.stringify(students));
}

Reading an input from a textbox and storing it in an array in JavaScript

I have a <textarea> that allows text to be inputted in the form of a string. Then the users clicks on a button which displays what they have inputted back to them in a text area within a table.
I need to use an array to store what has been inputted by the user, and then display it back out into another <textarea> element within a table from the array, where the user input is stored from the input box.
Any pointers on how to fill up an array and stacks, from a user input would be great.
You can declare your array like this
var yourArray = new Array();
or
var yourArray = [];
To add items to array:
yourArray.push(yourString);
To get you can use indexing like (almost any other language)
yourArray[i]
You can even set as an object array like this:
yourArray.push({ text : 'blablabla'})
So, in your case, filling up the array could be something like this:
var inputText = document.getElementById('id_of_input').value;
yourArray.push(inputText);
// show it
for(var i=0; i<yourArray.length; i++) {
alert(yourArray[i]);
}

store values from form to grid

I have create a add record form in extjs which stores user entered data into grid.
Well , if found following method to get form values from formPanel
var formPanel = new Ext.form.FormPanel({...});
var form = formPanel.getForm();
var firstName = form.findField('firstname').getValue();
but i want to covert all the user input value into JSON and want to store into Grid panel and want to send it to the server also. but using findField i have to manually create the array and then need to encode it into JSON , so is there any alternate way to directly read values from form and convert it into JSON and store it into Grid Panel.
When you say "want to store in the GridPanel" would you be updating an existing record in the Grid's store or would you be inserting a new one or both? (depending on whether its add or update probably?)
For such situations, BasicForm (var form in your snippet above) provides updateRecord( Record record ) method.
So your steps would be -
var record = Record.create(...) // in case of insert
OR
var record = //obtain record from grid.getStore() in case of update
Then,
formPanel.getForm().updateRecord(record); //update the passed record with values from the form
Followed by committing the record back to the store-
grid.getStore().add(record); //in case of insert
grid.getStore().commitChanges(); //incase of update
Reference - Ext.form.BasicForm , Ext.data.Record
Define your record type -
MyRecordType = Ext.data.Record.create(['id', 'field1', 'field2']);
var myrec = new MyrecordType();
Now pass myrec to updateRecord as mentioned above.

Categories