store the localstorage value in the form of json - javascript

Hi I am trying to save some input[type="text"] and input[type="hidden"] values in local storage. Below is the JS:
$('.proceed_btn').on('click', function(){
$('input[type="text"]').each(function(){
var id = $(this).attr('id');
var value = $(this).val();
localStorage.setItem(id, value);
});
$('input[type="hidden"]').each(function(){
var id = $(this).attr('id');
var value = $(this).val();
localStorage.setItem(id, value);
});
});
The value are getting stored perfectly. But I want to store these value in json format. But how to save both these values in one variable. For example:
order: {
id: '',
product: '',
service: '',
name: ''
}
I have checked the JSON stringify but how to implement with different types of input together

Simply build an object and then stringify it. For instance, if I assume the name of your input elements is the name you want to use on your object:
$('.proceed_btn').on('click', function(){
// Blank to start with
var order = {};
// Loop through all inputs...
$('input[type="text"], input[type="text"]').each(function(){
// ...adding their values as properties
order[this.name] = this.value;
});
// Store that object in JSON format
localStorage.setItem("order", JSON.stringify(order));
});
Later if you want to retrieve it and set the inputs based on its values:
var order = JSON.parse(localStorage.getItem("order") || "null");
if (order) {
$('input[type="text"], input[type="text"]').each(function(){
if (this.name in order) {
this.value = order[this.name];
} else {
this.value = "";
}
});
}

There are only 2 parameters will be there while writing localstorage:
ex.
localStorage.setItem( 'car', car );
1st parameter is key actually and 2nd parameter is value;
You have passed 3 paramters which is wrong.
If you can to store multiple values in localstorage, create object of that values and write that object to localstorage:
ex.
var car = {};
car.wheels = 4;
car.doors = 2;
car.sound = 'vroom';
car.name = 'Lightning McQueen';
console.log( car );
localStorage.setItem('car', JSON.stringify(car));
console.log( JSON.parse( localStorage.getItem( 'car' ) ) );

I think this will help.
var objectToSave = {};
$('.proceed_btn').on('click', function(){
$('input[type="text"],input[type="hidden"]').each(function(){
var elem = $(this);
var id = elem.attr('id');
var value = elem.val();
objectToSave[id] = value;
});
localStorage.setItem('order', JSON.stringify(objectToSave));
});

Related

Dynamically append Javascript variable to URL

Im attempting to produce a dynamic url containing multiple javascript variables but i only want to include them if they contain information.
These variables are essentially filters which will be used to Select from a MYSQL databse so they take form of "column=value".
The url i am trying to produce will need to be in the format of
page.php?column1=value1&column2=value2.... etc.
i am struggling to work out how to include only the variables that contain info and then how to insert the required "&" between each variable.
The current code is below and currently contains just the two variabls but the aim is to have as many as 5.
var jsedibility = "";
function chosenEdibility(choice){
jsedibility = choice;
}
var jsfrequency = "";
function chosenFrequency(choice2){
jsfrequency = choice2;
}
function setFilters(){
window.location='search.php?' + jsedibility+"&"+jsfrequency;
}
i am then using "onClick=setFilters()" assigned to a button to load the relevant page.
How can i set this up so that the URL is produced dynamically, only containing the variables that have data in them and also to add the required "&" between each variable.
Massively appreciate any help :)
I would make an array of the variables then use join().
var filters = [];
Use an if statement to check that they are not empty strings.
if (jsedibility != ""){ filters.push(jsedibility) }
var filtersString = filters.join('&');
Then in your setFilters(),
window.location.assign('./' + filtersString)
This works with any number of variables.
// mockup data object
const obj = {
jsedibility: '',
jsfrequency: '',
jsvar1: '',
jsvar2: '',
jsvar3: ''
}
// setting object values
function setObjVal(obj) {
obj.jsedibility = 'choice1'
obj.jsfrequency = 'choice2'
}
// creating the filter string
function setFilters(obj) {
return Object.values(obj).filter(val => val !== '').join('&')
}
document.getElementById('setFilters').addEventListener('click', function(e) {
setObjVal(obj)
console.log(setFilters(obj))
})
<button id="setFilters">Filters</button>
Or another with an array:
// mockup data
const choice = 'ch1'
const choice2 = 'ch2'
const array = []
var jsedibility = "";
function chosenEdibility(choice) {
jsedibility = choice;
}
var jsfrequency = "";
function chosenFrequency(choice2) {
jsfrequency = choice2;
}
// showing that it can be filtered out
var noValue = "";
function chosenNoValue(choice3) {
noValue = choice3;
}
chosenEdibility(choice)
chosenNoValue('') // empty value
chosenFrequency(choice2)
document.getElementById('setFilters').addEventListener('click', function(e) {
array.push(jsedibility)
array.push(noValue)
array.push(jsfrequency)
// string filtered for not empty values
const filterString = array.filter(el => el !== '').join('&')
console.log(filterString)
})
<button id="setFilters">Filters</button>

get Input values dynamically in jquery

I am devolping a web application using symfony framework. I have aproblem in forms. Here is my code:
$('#bookCleaningForm').submit(function() {
// get the array of all the inputs
var $inputs = $('#bookCleaningForm :input[type=text]');
// get an associative array of the values
var values = {};
var allVAlues='';
$inputs.each(function() {
values[this.name] = $(this).val();
allVAlues = values[this.name];
});
alert(allValues);//console.log(allValues);
saveBoookCleaning(allVAlues);
});
In the loop i got all data in allValues variable.But when I access outside the loop i got only one value.
Please help
Each time in the each loop you are assigning the variable allValues to the value of the current input. If you want to store the values as an array you could do this:
$('#bookCleaningForm').submit(function() {
// get the array of all the inputs
var $inputs = $('#bookCleaningForm :input[type=text]');
// get an associative array of the values
var values = {};
var allVAlues=[];
$inputs.each(function() {
values[this.name] = $(this).val();
allVAlues.push(values[this.name]);
});
alert(allVAlues);//console.log(allValues);
saveBoookCleaning(allVAlues);
});
Or, if you want them as a string:
$('#bookCleaningForm').submit(function() {
// get the array of all the inputs
var $inputs = $('#bookCleaningForm :input[type=text]');
// get an associative array of the values
var values = {};
var allVAlues='';
$inputs.each(function() {
values[this.name] = $(this).val();
allVAlues += values[this.name];
});
alert(allVAlues);//console.log(allValues);
saveBoookCleaning(allVAlues);
});

Adding an array to a Javascript object

I have some code I want to put into a JSON object ultimately. But first I want to create a javascript object and within that object add an array of values. Sounds simple enough but my approach seems wrong. First I create a basic object, the set a few fields. Lastly, iterate over a bunch of checkboxes and then, if one is checked at that value to an array.
At the last step I need to add that array to my object (myData) and then JSONify it.
Any ideas how I can do this, seems myData.push(filters); doesn't work...
Note that the object itself is not an array, I want to place an array IN the object.
var myData = new Object();
myData.deviceId = equipId;
myData.dateTo = dateTo
myData.dateFrom = dateFrom;
myData.numResults = $("#numResults").val();
var i=0;
var filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
filters[i] = {
filterIds: $(this).val()
};
++i;
}
});
myData.push(filters);
That's not how to add items to an Object, change
myData.push(filters);
to
myData.filters = filters;
Also, maybe change = new Object to = {}. There's no difference, but it's easier to read, because literal notation takes up less space.
Read more about Array.prototype.push
Use push to add elements to the filters array. Use property assignment to add another property to the myData object.
var myData = {
deviceId: equipId,
dateTo: dateTo,
dateFrom: dateFrom,
numResults: $("#numResults").val()
};
var filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
filters.push({
filterIds: $(this).val()
});
}
});
myData.filters = filters;
BTW, don't use new Object() to create an object, use {}.
Remove the need for an extra array and i.
var myData = {}
myData.deviceId = equipId;
myData.dateTo = dateTo
myData.dateFrom = dateFrom;
myData.numResults = $("#numResults").val();
myData.filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
myData.filters.push({
filterIds: $(this).val()
});
}
});

javascript dynamically add values to array

I'm trying to loop over the checkboxes in a form and add their values to a multidimensional javascript object. The 'attrib' data attribute will be the key. Possible key values are 'category', 'product_group' and 'language' but I'd rather add them dynamically in case any more get added in the future.
I want to end up with an object like this, which I can easily send as a json_encode 'd single value to the server.
values = {
'category' : {1,2,3},
'product_group' : {4,5,6},
'language': {'en','fr','de'}
};
Code below. Here obviously each iteration overwrites existing values instead of adding to it. I'm unsure where I can create values[key] as an object ... ?
$('.filter input, .multiselect-container input').change(function() {
var values = {}
$('.filter input:checked').each(function() {
if($(this).is(':checked')) {
var key = $(this).data('attrib')
var value = $(this).val()
values[key] = value
// values[key].push(value) = calling method push of undefined ...
}
else {
// Remove value
}
})
console.log(values)
})
Your error is due to the fact that values[key] is undefined, therefore does not have a push method.
Try this code:
if($(this).is(':checked')) {
var key = $(this).data('attrib')
var value = $(this).val()
values[key] = values[key] || [] // initialize with empty array
values[key].push(value)
}
Not sure that's what you are looking for:
if(!values[key])
values[key]=new Array();
values[key].push(value);
But this way you can add an array of value to every key.
Try this:
if($(this).is(':checked')) {
var key = $(this).data('attrib')
var value = $(this).val()
if(typeof values[key] == "undefined")
values[key] = [];
values[key].push(value);
}
else {
// Remove value
}
First, your data representation is not correct. The object attributes should be arrays like this:
values = {
'category' : [1,2,3],
'product_group' : [4,5,6],
'language': ['en','fr','de']
};
With that data representation, this piece of code will do what you want:
$('.filter input, .multiselect-container input').change(function() {
var values = {}
$('.filter input:checked').each(function() {
if($(this).is(':checked')) {
var key = $(this).data('attrib')
var value = $(this).val()
values[key] = value
if (values.key == undefined){
//Check if key exists. If not, create it as an array
values[key] = Array()
values[key].push(value)
}
else{
values[key].push(value)
}
}
else {
// Remove value
}
})
console.log(values)
})

Javascript - How do I declare a variable with the variable name based on a string?

var cur_storage_unit = $('#storage_unit').val();
$('.size_unit').change(function() {
var id = $(this).attr('id');
//This is how I want it to work, but not sure how
'cur_' + id = $(this).val();
});
The user 'changes' a of class 'size_unit' and id of 'storage_unit'. I want to then set the value of 'cur_storage_unit' to the new value of 'storage_unit'. In italics is how I want it to work, but I'm not sure the syntax of how to get it to work. Thanks!
You're probably better off using an Object, and storing it in there.
var cur_storage_unit = $('#storage_unit').val();
var values = {}; // storage for multiple values
$('.size_unit').change(function() {
var id = this.id;
values['cur_' + id] = this.value; // store this value in the "values" object
});
// Accessible via values object
alert( values["cur_theid"] );
you can create a new property on an object using a string as a key
var myObj = {};
myObj['cur_'+id] = $(this).val();
so in your case you would want an object with a known name where you can add dynamically named properties.
If it's global you can do window['cur_'+id];

Categories