Can you please help with my problem
I have the following JavaScript object:
var data = {
'rows[0][name]': 'foshka',
'rows[0][tel]': '096',
'rows[0][opt]': 'none'
};
The problem is that i get an error while trying to pass variable as rows index:
var i = 0;
var data = {
'rows['+ i +'][name]': 'one',
'rows['+ i +'][tel]': '096',
'rows['+ i +'][opt]': 'none'
};
Thanks in advance
Your code has to be
var data = {};
data[ 'rows['+ i +'][name]' ] = 'one';
data[ 'rows['+ i +'][tel]' ] = '069';
However you might want to change your structure to sth like this:
var data ={};
var i = 0;
data['rows'][i]['name'] = 'one';
Or even cleaner:
var data = { rows[] };
var i = 0;
data['rows'][i] = { 'name' : 'one', 'tel' : 069' };
// so you can access them like this:
alert ( data['rows'][i]['name'] );
I think your data should look like this:
var data = {
rows: [{
name: 'one',
tel: '096',
opt: null
}]
};
That way you can simply add new rows if needed.
Related
I need to combine all variables in one object:
$.get("https://www.virginmegastore.ae/en/gaming/playstation/playstation-games/sonic-forces---ps4/p/714792", function (data) {
var productNamePost=$("[name='productNamePost']").val();
var productCodePost=$("[name='productCodePost']").val();
var bg = $('.pdp_image-carousel-image.js-zoomImage-mobile').css('background-image');
var productPrice=$(".price__container > .price__value > .price__number").text();
var url = window.location.href;
console.log(url);
});
Sorry the question was unclear,i was need this
let obj = Object.assign({},var)
I also need to run the code when the button clicked
$.get("https://www.virginmegastore.ae/en/gaming/playstation/playstation-games/sonic-forces---ps4/p/714792", function (data) {
$("#addToCartForm > #addToCartButton").click(function(){
var productNamePost=$("[name='productNamePost']").val();
var productCodePost=$("[name='productCodePost']").val();
var bg = $('.pdp_image-carousel-image.js-zoomImage-mobile').css('background-image');
var productPrice=$(".price__container > .price__value > .price__number").text();
var url = window.location.href;
let obj = Object.assign({}, [productNamePost, productCodePost, bg, productPrice, url]);
console.log(obj)});
});
but i got below error when i clicked the button:
Try this:
let obj = Object.assign({}, [
productNamePost: $("[name='productNamePost']").val(),
productCodePost: $("[name='productCodePost']").val(),
bg: $('.pdp_image-carousel-image.js-zoomImage-mobile').css('background-image'),
productPrice: $(".price__container > .price__value > .price__number").text(),
url: window.location.href
]);
This will create an object array with all your variables. Read more about Object.assign() here
Like this?
var newObj = {
"productNamePost": $("[name='productNamePost']").val(),
"productCodePost": $("[name='productCodePost']").val(),
"variable_name": variable_value
}
My Controller Function:
public function displayAction(Request $request)
{
$stat = $this->get("app_bundle.helper.display_helper");
$displayData = $stat->generateStat();
return new JsonResponse($displayData);
}
My JSON Response from URL is:
{"Total":[{"date":"2016-11-28","selfies":8},{"date":"2016-11-29","selfies":5}],"Shared":[{"date":"2016-11-28","shares":5},{"date":"2016-11-29","shares":2}]}
From this Response I want to pass the values to variables (selfie,shared) in javascript file like:
$(document).ready(function(){
var selfie = [
[(2016-11-28),8], [(2016-11-29),5]]
];
var shared = [
[(2016-11-28),5], [(2016-11-29),2]]
];
});
You can try like this.
First traverse the top object data and then traverse each property of the data which is an array.
var data = {"total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2},{"date":"2016-11-30","selfies":0},{"date":"2016-12-01","selfies":0},{"date":"2016-12-02","selfies":0},{"date":"2016-12-03","selfies":0},{"date":"2016-12-04","selfies":0}],"shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0},{"date":"2016-11-30","shares":0},{"date":"2016-12-01","shares":0},{"date":"2016-12-02","shares":0},{"date":"2016-12-03","shares":0},{"date":"2016-12-04","shares":0}]}
Object.keys(data).forEach(function(k){
var val = data[k];
val.forEach(function(element) {
console.log(element.date);
console.log(element.selfies != undefined ? element.selfies : element.shares );
});
});
Inside your callback use the following:
$.each(data.total, function(i, o){
console.log(o.selfies);
console.log(o.date);
// or do whatever you want here
})
Because you make the request using jetJSON the parameter data sent to the callback is already an object so you don't need to parse the response.
Try this :
var text ='{"Total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2}],"Shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0}]}';
var jsonObj = JSON.parse(text);
var objKeys = Object.keys(jsonObj);
for (var i in objKeys) {
var totalSharedObj = jsonObj[objKeys[i]];
if(objKeys[i] == 'Total') {
for (var j in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"selfies on "+totalSharedObj[j].date+":"+totalSharedObj[j].selfies+"<br>";
}
}
if(objKeys[i] == 'Shared') {
for (var k in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"shares on "+totalSharedObj[k].date+":"+totalSharedObj[k].shares+"<br>";
}
}
}
<div id="demo">
</div>
I did a lot of Research & took help from other users and could finally fix my problem. So thought of sharing my solution.
$.get( "Address for my JSON data", function( data ) {
var selfie =[];
$(data.Total).each(function(){
var tmp = [
this.date,
this.selfies
];
selfie.push(tmp);
});
var shared =[];
$(data.Shared).each(function(){
var tmp = [
this.date,
this.shares
];
shared.push(tmp);
});
});
Hi i am new in javascript before i read the case split using the function. I just followed but not understand it. Can you guys give me a link or guide to explain how it work? tks a ton
var first = getUrlVars()["id"];
var second = getUrlVars()["page"];
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
This function return the value of each varrian from url.
In your code, you want to get id, page from url. I guest you have a url like : your-page?id=value&page=value, and you want to get them, don't you?
You need to read the replace function at http://www.w3schools.com/jsref/jsref_replace.asp
There is a kind of function you would like. Hope you will understand this :
var getUrlVars = function( url ){
if( !url.match( /\?/ ) ) return {};
var paramsfull = url.replace( /^.*\?/, "" ).split( /\&/g );
var params = {};
var _temp;
for( var p in paramsfull ){
_temp = paramsfull[ p ].split( /\=/ );
params[ _temp[ 0 ] ] = _temp[ 1 ];
}
return params;
}
var first = getUrlVars( window.location.href )[ "id" ];
var second = getUrlVars( window.location.href )[ "page" ];
I'm working on a form that is saved by HTML5 local storage.
When pressing save:
function saveAll(){
var field1 = document.getElementById('field1').value;
localStorage.setItem('con_field1',field1);
var field2 = document.getElementById('field2').value;
localStorage.setItem('con_field2',field2);
var field3 = document.getElementById('field3').value;
localStorage.setItem('con_field3',field3);
var field4 = document.getElementById('field4').value;
localStorage.setItem('con_field4',field4);
var field5 = document.getElementById('field5').value;
localStorage.setItem('con_field5',field5);
var field6 = document.getElementById('field6').value;
localStorage.setItem('con_field6',field6);
}
And when loading the page (fills out the forms):
function ShowAll() {
var field1 = localStorage.getItem('con_field1');
document.conditioning.field1.value = field1;
var field2 = localStorage.getItem('con_field2');
document.conditioning.field2.value = field2;
var field3 = localStorage.getItem('con_field3');
document.conditioning.field3.value = field3;
var field4 = localStorage.getItem('con_field4');
document.conditioning.field4.value = field4;
var field5 = localStorage.getItem('con_field5');
document.conditioning.field5.value = field5;
var field6 = localStorage.getItem('con_field6');
document.conditioning.field6.value = field6;
}
This all works fine, but I want to re-write this in a more fancy and efficient way. I was thinking of something like this:
function ShowAll() {
var field = [];
for (i=0; i<6; i++) {
field[i] = localStorage.getItem(window['con_field' + i]);
document.purpose.field[i].value = window['con_field' + i]
}
}
But the browser is not enjoying this. Basically I need to create a loop that automatically changes the "field" name in to 'field1, field2, field3' etc. The window thing is working, but I'm just using it wrong.
Anyone has an idea?
Thanks a lot!
function showAll(t1,c1,d1) {
var field1 = localStorage.getItem('con_field1');
console.log(field1)
var field2 = localStorage.getItem('con_field2');
var field3 = localStorage.getItem('con_field3');
}
You should add all of your data to one object, stringify it, then add that to local storage under a single key.
When you load it, grab the one local storage item, parse it, then access the properties on the object.
e.g.
var save = function () {
var data = {
foo: 'bar'
};
localStorage.setItem('myData', JSON.stringify(data));
};
var load = function () {
var data = JSON.parse(localStorage.getItem('myData'));
var someProp = data.foo; // gives you 'bar'
};
It looks like your main problem is that the fields are indexed beginning with 1, but your loop indexes from 0.
What about this?
var field = [];
for (i = 1; i <= 6; i++)
{
field[i] = localStorage.getItem(window['con_field' + i]);
document.purpose.field[i].value = window['con_field' + i]
}
Also, I'm not 100% on this, but I think using document.getElementByID is more cross-browser compatible than using bracket notation on the window object, but it's been a while since I wrote plain vanilla JS, so don't quote me.
I would try document.purpose["field" + i].value = window['con_field' + i].
Can someone tell me what the best way is to store content in an object literal and how to access it using my JS pattern? I can't seem to get it to work.
Namespace.object = {
var data = [{"myid1" : "<p>My content 1</p>"}];
method: function () {
var myData = Namespace.object.data[0].id;
}
};
To store:
Namespace.object = {
data: [{"myid1" : "<p>My content 1</p>"}],
method: function () {
var myData = Namespace.object.data[0].id;
}
};
To access:
var theFirstData = Namespace.object.data[0];
var myId1 = Namespace.object.data[0].myid1;
// Alternatively...
var myId1b = Namespace.object.data[0]['myid1'];
Namespace.object.method();