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
}
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);
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);
});
});
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();
Really a javascript question, but here's my code........I would truly appreciate some help. Been too long since I've been in the coding trenches. Here's my code.
I want to make loadtravelurl into a single function I can call from multiple places.
These three lines below are my issues.
win2.title = title;
win2.add(tv);
tab2.open(webwin);
I want to be able to pass variables in loadelectronicsurl function, where I can change the text win2 in win2.title and win2.add(tv) dynamically. Also want to do the same with tab2. I know it can be done, just had a few years off and forgot how to do so in javascript.
Here is the full code, thanks so much for the help in advance!
function loadelectronicsurl(){
var WindowWidth = Ti.Platform.displayCaps.platformWidth;
var WindowHeight = Ti.Platform.displayCaps.platformHeight;
var xhr = Titanium.Network.createHTTPClient();
xhr.open('GET',electronicsurl);
var data = [];
var WindowWidth = Ti.Platform.displayCaps.platformWidth;
xhr.onload = function() {
//Ti.API.info(this.responseText);
var xml = this.responseXML;
var channel = xml.documentElement.getElementsByTagName("channel");
var title = channel.item(0).getElementsByTagName("title").item(0).text;
win2.title = title;
var items = xml.documentElement.getElementsByTagName("item");
for (var i=0;i<items.length;i++) {
var this_post_title = items.item(i).getElementsByTagName("title").item(0).text;
var post_link = items.item(i).getElementsByTagName("link").item(0).text;
var row = Ti.UI.createTableViewRow({height:'auto',width:WindowWidth,top:0,hasChild: false});
var post_title = Ti.UI.createLabel({
text: this_post_title,
textAlign:'left',
left:0,
height:40,
font:{fontFamily:'Arial',fontSize:12},
width:'auto',
top:3,
color: 'black'
});
row.add(post_title);
row.link = post_link;
data.push(row);
}
var tv = Titanium.UI.createTableView({
data:data,
top:0,
width:WindowWidth,
height:WindowHeight
});
win2.add(tv);
tv.addEventListener('click',function(e) {
var webwin = Titanium.UI.createWindow({
url: 'showweb.js',
backgroundColor: '#fff',
myurl: e.rowData.link
});
tab2.open(webwin);
});
};
xhr.send();
}
You can define parameters for a function like this:
function someFunc(win, tab){
win.add();
tab.open();
}
You can also use the parameters to access properties of an object dynamically like this:
function someFunc(win, tab){
obj.[win](); //To call an object's method
obj.[tab]; //To access an object's property
}
Call the function and pass the paramters:
someFunc(someObject, anotherObject);
someObject becomes win and anotherObject becomes tab inside the function.