Translate a html attribute to javascript object - javascript

$("div").click(function () {
var obj = { flammable: 'inflammable', duh: 'no duh' };
$.each(obj, function (key, value) {
alert(key + ": " + value);
});
});
This works without problem and alerts key/value.
$("div").click(function () {
var obj = $(this).attr("obj");
$.each(obj, function (key, value) {
alert(key + ": " + value);
});
});
<div obj="{ flammable: 'inflammable', duh: 'no duh' }">click</div>
However this is not working?

change this line
var obj = $(this).attr("obj");
to
var obj = JSON.parse($(this).attr("obj"));
Also, you may want to use escaped double quotes rather than single quotes inside the object, make it
<div obj="{ \"flammable\": \"inflammable\", \"duh\": \"no duh\" }">click</div>
or
<div obj= '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}' >click</div>

Related

Chrome Console returning 8 Nan from variable

I am using the following function
function QuantityCheckout () {
var obj = {
"BackGlassQty": Cookies.get('BackGlassQty'),
"BackCameraQty": Cookies.get('BackCameraQty'),
"BatteryQty": Cookies.get('BatteryQty'),
"ChargingPortQty": Cookies.get('ChargingPortQty'),
"FrontCameraQty": Cookies.get('FrontCameraQty'),
"GlassCameraCoverQty": Cookies.get('GlassCameraCoverQty'),
"LogicBoardQty": Cookies.get('LogicBoardQty'),
"ScreenQty": Cookies.get('ScreenQty')
};
$.each(obj, function (key, value) {
var test = '#' + key - 'qty' + 'Quantity'
console.log(test);
$('#' + key - 'qty' + 'Quantity').text('Quantity:' + value);
});
}
and it keeps returning 8 in a circle and NaNQuantity.
There is no - operator for String in Js. Instead you should use the replace function, and so your code should become:
var test = '#' + key.replace('Qty', '') + 'Quantity'
It's because when you join the string you have a minus in there so it is trying to do a mathematical calculation instead, which is why you get NaN.
Use a + to concatenate the strings.
const Cookies = {
get: () => {}
}
function QuantityCheckout () {
var obj = {
"BackGlassQty": Cookies.get('BackGlassQty'),
"BackCameraQty": Cookies.get('BackCameraQty'),
"BatteryQty": Cookies.get('BatteryQty'),
"ChargingPortQty": Cookies.get('ChargingPortQty'),
"FrontCameraQty": Cookies.get('FrontCameraQty'),
"GlassCameraCoverQty": Cookies.get('GlassCameraCoverQty'),
"LogicBoardQty": Cookies.get('LogicBoardQty'),
"ScreenQty": Cookies.get('ScreenQty')
};
$.each(obj, function (key, value) {
var test = '#' + key + 'qty' + 'Quantity'
console.log(test);
$('#' + key + 'qty' + 'Quantity').text('Quantity:' + value);
});
}
QuantityCheckout()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Alternatively you can use back ticks
var test = `#${key}qtyQuantity`

jQuery JSON I continue to get [object Object] as a value

I was updating the script for my site to allow for API changes from v1 to v2 the changes being
V1
"ISteamClient": 0,
etc..
V2
"ISteamClient": {
"online": 1
},
etc..
But now when I write what val is for each of the parts I get [object Object] in return, so I found a guide in which I call val['online'] but I still get [object Object]. I haven't done much work with JSON, just simple first layer JSON (like V1)
function loadup() {
$.getJSON("https://steamgaug.es/api/v2", function(data) {
var items = [];
var ISteamClient = 2,
ISteamCommunity = 2,
ISteamGameCoorindator_440 = 2,
ISteamUser = 2,
IEconItems_440 = 2;
$.each(data, function(key, val) {
if (key === "ISteamClient") {
ISteamClient = val['online'];
console.log(key + " = " + val);
}
else if (key === "SteamCommunity") {
ISteamCommunity = val['online'];
console.log(key + " = " + val);
}
else if (key === "ISteamGameCoorindator_440") {
ISteamGameCoorindator_440 = val['online'];
console.log(key + " = " + val);
}
else if (key === "ISteamUser") {
ISteamUser = val['online'];
console.log(key + " = " + val);
}
else if (key === "IEconItems_440") {
IEconItems_440 = val['online'];
console.log(key + " = " + val);
}
});
//Sort and group data
});
}
What am I doing wrong?
You're logging val, which is an object.
I think you want to log val.online

loop a recieved json string to get values by jquery

I'm trying to parse data returned from $.post().
[{"id":"1","text":"USD"},
{"id":"2","text":"CNY"},
{"id":"3","text":"PHP"},
{"id":"4","text":"AUD"},
{"id":"5","text":"SGD"},
{"id":"6","text":"JPY"}]
using this approach Jquery, looping over a json array
I did something like this:
$.post(
base_url+'cgame/currency',
{ gameID: gameID },
function(data) {
$(this).html();
$.each(data,function(idx, obj) {
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
});
}
);
but it gives me the error:
Uncaught TypeError: Cannot use 'in' operator to search for '120' in [{"id":"2","text":"CNY"},{"id":"3","text":"PHP"},{"id":"4","text":"AUD"},{"id":"5","text":"SGD"},{"id":"6","text":"JPY"}]
I also tried:
$.post(
base_url+'cgame/currency',
{ gameID: gameID },
function(data) {
$(this).html();
$(data).each(function(idx, obj) {
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
});
}
);
but it also gives me the error:
Uncaught Error: Syntax error, unrecognized expression: [{"id":"1","text":"USD"},{"id":"6","text":"JPY"}]
How should I be doing this?
Your data comes in the form of array so you need to loop through each index and then fetch the values. So you can replace this :-
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
with :-
$.each( obj, function( key) {
console.log( obj[key].id + ':' + obj[key].text);
});
or you can do this :-
$.each( obj, function( key, value ) {
console.log( value.id + ':' + value.text);
});
key is the index of array. It will return 0,1,2..
I think the argument passed to your success callback function is of type string. Change it to:
function(data) {
var parsedData = JSON.parse(data);
$(this).html();
$.each(parsedData ,function(idx, obj) {
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
});
}
function(data) {
var value = JSON.parse(data);
$.each(value ,function(idx, obj) {
console.log("id : "+obj.id+" "+text:"+obj.text);
});
}
try this
$.post(base_url+'cgame/currency',{ gameID: gameID },
function(data) {
$(this).html(); //<-- becareful $(this) might not be the element you think it is
$.each(data,function(idx, obj) {
console.log( "id : " + obj.id);
console.log( "text: " + obj.text);
});
},'JSON');

search with an array associate with javascript?

I want to do a search by name and surname with an array javascript, and the results in a div. for example: I write Ali in input, an it shoul show me Alison and Alibaba.
this is my code, but it's giving errors; are there other ways to do it?:
<input type='text' id='filter' placeholder='search'>
<div id='output' style='margin-top:50px '></div>
my array
var arrayD =[
{"Name":"Alison","Surname":"Kenn","Mobile":529129293},
{"Name":"Ashton","Surname":"Jhojan","Mobile":529129293},
{"Name":"Bith","Surname":"Klint","Mobile":129129293},
{"Name":"Ana","Surname":"Clow","Mobile":229129293},
{"Name":"Geoge","Surname":"Rich","Mobile":329129293},
{"Name":"kenneth","Surname":"Cooler","Mobile":329129}
]
var $result = $('#output');
$('#filter').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {
console.log( item[0].toLowerCase().indexOf(val));
if ( item[0].toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<li>' + item[0] + ' ' + item[1] + '</li>');
}
});
$result.html( $fragment.children() );
});
http://jsfiddle.net/henrykend/ChpgZ/4/
The main problem with your code is that you're trying to reference fields in the object by ordinal position rather than name. There is nothing automagic in JavaScript which will read item.Name (or item["Name"]) from item[0].
There is also no need to build up a "false element" (in your case $fragment) and then append its children to the output area - you may as well do this in one go (remembering to .empty() it between calls).
Your corrected code:
var $result = $('#result');
$('#output').on('keyup', function () {
$result.empty();
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {
if ( item.Name.toLowerCase().indexOf(val) == 0 ) {
$result.append('<li>' + item.Name + ' ' + item.Surname + '</li>');
}
});
});
And a live example: http://jsfiddle.net/ChpgZ/6/
You had couple of problems in your code.
Names of the elements we're wrongly placed (which you've fixed with the edit)
In the .each, you've used item[0] instead of item.Name (also surname)
See the following code
var arrayD =[
{"Name":"Alison","Surname":"Kenn","Mobile":529129293},
{"Name":"Ashton","Surname":"Jhojan","Mobile":529129293},
{"Name":"Bith","Surname":"Klint","Mobile":129129293},
{"Name":"Ana","Surname":"Clow","Mobile":229129293},
{"Name":"Geoge","Surname":"Rich","Mobile":329129293},
{"Name":"kenneth","Surname":"Cooler","Mobile":329129}
]
var $result = $('#result');
$('#output').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {console.log( item.Name.toLowerCase().indexOf(val) );
if ( item.Name.toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<li>' + item.Name + ' ' + item.Surname + '</li>');
}
});
$result.html( $fragment.children() );
});

jQuery JSON looping through nested objects

I currently have this:
$.getJSON('test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
test.json looks like this:
{"key1":{"key11":"value11","key12":"value12"},"key2":"value2","key3":"value3"}
I'm getting:
[object Object]
value2
value3
How can I change it so it will loop through all the nested items regardless of how many nested values I have?
So for the above example I will get
value1
value11
value12
value2
value3
You can make a recursive loop function, but you'd have a problem: when a property is an object, there is no text to display because there is no string. So, you'll end up with:
- - value11
- value12
- value2
- value3
because while value2 is the string to display for item #2, it is an object that's displayed for item #1.
Anyway, this is what I made up: http://jsfiddle.net/uXww2/.
// obj is the object to loop, ul is the ul to append lis to
function loop(obj, ul) {
$.each(obj, function(key, val) {
if(val && typeof val === "object") { // object, call recursively
var ul2 = $("<ul>").appendTo(
$("<li>").appendTo(ul)
);
loop(val, ul2);
} else {
$("<li>", {
id: key
}).text(val).appendTo(ul);
}
});
}
$.getJSON('test.json', function(data) {
var ul = $("<ul>");
loop(data, ul);
ul.addClass("my-new-list").appendTo('body');
});
so, what you want is a treeview looping through a json object
you can use this code i made myself recursively, test it ;)
var treestring = "";
var myid = "arv";
var json_object = {your json};
var Tree = function (data) {
this.data = data;
};
//1st step
Tree.renderTree(json_object, myid);
//2st step , this is a function
Tree.renderTree= function (json_object, myid) {
$.each(json_object, function (key, val) {
var m = new Tree(val);
m.render(myid);
});
}
//3st step, this a function too
Tree.prototype.render = function (myid) {
treestring = "<li class='category'> " + this.data.Name;
//Check if has another arrays inside the current
if (this.data.SubFolders) {
treestring += "<ul id=" + this.data.ID + "</ul>";
$("#" + myid).append(treestring);
myid = this.data.ID;
Tree.renderTree(this.data.Sub_Fodlers, myid);
}
else {
treestring += "</li>";
$("#" + myid).append(treestring);
}
};
//HTML
<div id="tree">
<ul id="arv"></ul>
</div>
//this.data.{something} ate the fields defined in your json object
enjoy ;)

Categories