I'm having trouble getting form data into an object in the structure I want. currently it returns in this format:
mainObject = { name1:{}, name2:{}, name3{} }
what I am trying to achieve is
mainObject = { {name1:{}}, {name2:{}}, {name3{}} }
my js:
var users = {};
function formSubmit(){
var name = $("#name").val();
var age = $("#age").val();
var zip = $("#zip").val();
users[name] = {};
users[name].age = age;
users[name].zip = zip;
console.log(users);
};
I have a bin available if that helps, thanks!
https://jsbin.com/bofohabahu/1/edit?html,js,console,output
An object can be seen as a collection of keys and values. An object cannot contain a value (like an object) without also having a key for that value (think about it, how would you access it?).
So that's why { {name1:{}}, {name2:{}}, {name3{}} } isn't possible.
If you don't care about having keys for each of the objects, then may I suggest using an array instead? [ {name1:{}}, {name2:{}}, {name3: {}} ]
this is how you make the name as a key containing the age and zip
var users = {};
function formSubmit(){
var name = $("#name").val();
var age = $("#age").val();
var zip = $("#zip").val();
users[name] = {
age: age,
zip: zip
};
console.log(JSON.stringify(users));
};
try this
https://jsbin.com/vanusapixu/1/edit?html,js,console,output
Related
Objects are being saved into localstorage and I want to retrieve that object and append to the page, also I want to change key name everytime new form is submitted, so at first key = key and then on next form submit I want key = key1 etc.
However I do not know how to achieve that, can someone help me?
var existingData = JSON.parse(localStorage.getItem("key")) || [];
$('body').append(existingData);
$('form').submit(function() {
var newArray = [];
$(".add_id2").each(function(){
newArray.push($(this).val());
});
var newArray2 = [];
$(".add_id").each(function(){
newArray2.push($(this).val());
});
var newData = {
'title': $("#title").val(),
'ingredients': $("#ingredients").val(),
'instructions': $("#inst").val(),
'moreingredients': newArray,
'moreinstruction': newArray2,
'img': img,
};
existingData.push(newData);
localStorage.setItem("key", JSON.stringify(existingData));
You can make the constructor function and call that with the new keyword...Please have a look at this. Hope this will help you.
Example:-
function formData(title, ingredients, instructions, moreingredients, img) {
this.title = title;
this.ingredients = ingredients;
this.instructions = instructions;
this.moreingredients = moreingredients;
this.img = img;
}
var newData = new formData($("#title").val(), $("#ingredients").val(), $("#inst").val(), newArray, newArray2);
I am storing my data from a form in localstorage in the following format:
Object {title: "dsadasds", dueDate: "dsadasdsa", summary: "dsadadas", body: "dasdasdas"}
Object {title: "dasdadsa", dueDate: "dasdasdadasda", summary: "dsadasdasd", body: "dasdasdas"}
This data is stored in localstorage every time a user submits the form. Now in a different page 'localhost:3000/notes' i wanna show all these objects stored in localStorage. Currently with the following code, its just showing the last object submitted.
var form = $('#form'),
formTitle = $('#title'),
formDueDate = $('#dueDate'),
formSummary = $('#summary'),
formBody = $('#body');
var title = formTitle.val();
var dueDate = formDueDate.val();
var summary = formSummary.val();
var body = formBody.val();
var newContent2 = $('#new-content2')
var test = {};
test = {
title: title,
dueDate: dueDate,
summary: summary,
body: body
}
localStorage.setItem('test', JSON.stringify(test));
var LocalStoredData = JSON.parse(localStorage.getItem('test'));
console.log(LocalStoredData);
//for retrieving data from locastorage
var retrievedData = localStorage.getItem('test');
var text = JSON.parse(retrievedData);
var showTitle = text["title"];
var showDueDate= text["dueDate"];
var showSummary = text["summary"];
var showBody = text["body"];
$('#showTitle').html(showTitle);
$('#showDueDate').html(showDueDate);
$('#showSummary').html(showSummary);
$('#showBody').html(showBody);
I need to loop trough all the objects (or any other mechanism) to extract all the objects from localStorage and display them in appropriate div on the web page. I tried putting the retrieval code in the loop:
for(var i=0;i<localStorage.length;i++)
but using this loop its not showing anything. How can I show all the objects present in my localStorage.
You're looking for
for (var i=0; i<localStorage.length; i++) {
var key = localStorage.key(i);
var item = localStorage.getItem(key);
try {
item = JSON.parse(item);
} catch(e) {
console.log(key+" is not in JSON format");
}
…
}
You can also easily get all the contents of LocalStorage using Object.keys:
Object.keys(localStorage).forEach(key => {
console.log(key, localStorage.getItem(key))
})
what i need
i need to store more then data in array , such user click on div respective data must be stored in array.
like
id: 1223, city:'chicago',
id:12333,city:' new york';
code
function favaorite(sess_id,name,city,country,event_url,pointer)
{
/* store imageurl in localstorage */
var imageUrl='/images/star1_phonehover.png';
// Save data to the current local store//
// Put the object into storage
localStorage.setItem('id' ,JSON.stringify(sess_id));
// Put the object into storage
localStorage.setItem('name' ,JSON.stringify(name));
// Put the object into storage
localStorage.setItem('city',JSON.stringify(city));
// Put the object into storage
localStorage.setItem('country',JSON.stringify(country));
// Put the object into storage
localStorage.setItem('event_url',JSON.stringify(event_url));
// Put the object into storage
localStorage.setItem('imageUrl',JSON.stringify(imageUrl));
step 2.
/* fetch the data using from localstorage */
var id= [];
var name= [];
var city = [];
var country =[];
var event_url= [];
// Retrieve the object from storage
//var id, city, country,event_url;
var id = localStorage.getItem('id');
console.log(id);
id = JSON.parse(id);
var name = localStorage.getItem('name');
name = JSON.parse(name);
console.log(name);
var name = localStorage.getItem('name');
name = JSON.parse(name);
var city = localStorage.getItem('city');
city = JSON.parse(city);
console.log(city);
var country = localStorage.getItem('country');
country = JSON.parse(country);
console.log(country);
var event_url = localStorage.getItem('event_url');
event_url = JSON.parse(event_url);
///console.log(event_url);
var image_url = localStorage.getItem('imageUrl');
//event_url = JSON.parse(event_url);
alert(image_url);
console.log(image_url);
here is snapshot :
i need to store more then string in array.
i have tried by console.log(id.length)//undefined.
i have also looked loop to store more values in localstoarge.
for (var i = 0; i < localStorage.length; i++) {
console.log(localStorage.key(i))
};
You can stringify entire object and save everything at once:
localStorage.setItem('event', JSON.stringify({
id: sess_id,
name: name,
city: city,
country: country,
event_url: event_url,
imageUrl: imageUrl
}));
It will also make the code simpler and shorter:
function favaorite(sess_id, name, city, country, event_url, pointer) {
/* store imageurl in localstorage */
var imageUrl = '/images/star1_phonehover.png';
// Save data to the current local store//
if (typeof (localStorage) == 'undefined') {
console.log('Your browser does not support HTML5 localStorage. Try upgrading.');
} else {
try {
// Put the object into storage
localStorage.setItem('event', JSON.stringify({
id: sess_id,
name: name,
city: city,
country: country,
event_url: event_url,
imageUrl: imageUrl
}));
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
}
}
And retrieving saved event data you can simply do reverse:
var eventData = JSON.parse(localStorage.getItem('event'));
Try like this,
U have to create an object and fill the details on every click, push that object into an array and store that array in local storage by using JSON.stringify().
And while retrieving again parse that JSON using JSON.parse().
function favaorite(sess_id,name,city,country,event_url,pointer){
var eventData = JSON.parse(localStorage.getItem('eventData '));
if(eventData ==null){
eventData=[];
}
Var details={};
details["sess_id"]=sess_id;
details["name"]=name;
details["city"]=city;
details["country"]=country;
details["event_url"]=event_url;
details["pointer"]=pointer;
eventData.push(details);
localStorage.setItem('eventData', JSON.stringify(eventData));
}
While retrieving parse the string to json u'll get the array of those click event details.
var EventDetails=JSON.parse(localStorage.getItem('eventData '));
First of all, I'm a complete JS novice. I'm experimenting with Meteor.My objective is to to build a simple form that inserts records into a table. I've set up variables to grab values from each input, and I've placed those variables into an insert method. When I click the button, it recognizes the click, but doesn't pull any values from the inputs. I'm sure I'm missing something simple here, I just can't figure out what it is.
Here's the JS:
var Leads = new Meteor.Collection("Leads");
if (Meteor.is_client) {
Template.Leads.LeadsArr = function(){
return Leads.find();
};
Template.AddLeads.events = {
"click input.submit" : function () {
var name = document.getElementById('input#name').value();
var email = document.getElementById('#email').value();
var type = document.getElementById('#type').value();
var date = document.getElementById('#date').value();
var message = document.getElementById('#message').value();
Leads.insert({leadName : name, leadEmail : email, leadType : type, leadDate : date, leadComment : message});
}
};
} // end is_client
document.getElementById expect the id, not the selector. Also, value is a property of an input, not a function. So your input queries should be like this.
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var type = document.getElementById('type').value;
var date = document.getElementById('date').value;
var message = document.getElementById('message').value;
I'm trying to parse the rows in a table that I generate using Javascript by adding items to a cart and then create a json object when the user hits save order of all the items and pass it to a php script using $.post in jQuery.
The only trouble I'm having is understanding JSON objects and how to push more items onto the object. I get an error in firebug telling me that devices[i] is undefined. Not really sure how else to accomplish this. I thought it was really just an array.
function Save()
{
var devices = new Object();
var i = 0;
$("#device_tbl tr:gt(0)").each(function(){
var manufid = $(this).find("td").eq(0).find(".manuf_id").html();
var modelid = $(this).find("td").eq(1).find(".model_id").html();
var condition = $(this).find("td").eq(2).find("select").val();
var carrier = $(this).find("td").eq(3).find("select").val();
var imei = $(this).find("td").eq(4).find("input").val();
var price = $(this).find("td").eq(5).html();
alert(manufid+"\n"+modelid+"\n"+carrier+"\n"+imei+"\n"+price);
devices[i].manufid = manufid;
devices[i].modelid = modelid;
devices[i].carrier = carrier;
devices[i].imei = imei;
devices[i].price = price;
i++;
});
document.write(devices); //just for debugging
$("#final").show();
}
You currently have devices declared as an object, but you're treating it like an array.
You need to declare it as an array of objects.
function Save()
{
var devices = new Array();
var i = 0;
$("#device_tbl tr:gt(0)").each(function(){
var manufid = $(this).find("td").eq(0).find(".manuf_id").html();
var modelid = $(this).find("td").eq(1).find(".model_id").html();
var condition = $(this).find("td").eq(2).find("select").val();
var carrier = $(this).find("td").eq(3).find("select").val();
var imei = $(this).find("td").eq(4).find("input").val();
var price = $(this).find("td").eq(5).html();
alert(manufid+"\n"+modelid+"\n"+carrier+"\n"+imei+"\n"+price);
devices[i] = new Object();
devices[i].manufid = manufid;
devices[i].modelid = modelid;
devices[i].carrier = carrier;
devices[i].imei = imei;
devices[i].price = price;
i++;
});
document.write(devices); //just for debugging
$("#final").show();
}
or something like that.
(Updated to show it in your code)