i have this simple jquery script to loop through JSON array
the script is not working at it all and never give output.
im sure that the JSON array is valid but i don't know why Jquery not parsing it .
$(document).ready(function(){
var cost = [{"gold":"100","iron":"80","wood":"120","food":"70"},{"gold":"80","iron":"60","wood":"90","food":"35"}];
var costarr = $.parseJSON(cost);
$.each(costarr, function(i, item) {
alert(item.gold);
}
});
You don't need to parse it, it's already an array. And your each lacks a closing )
$.each(cost, function(i, item) {
alert(item.gold);
}); //<-- lacking ")"
You have a syntax error.
$.each(costarr, function(i, item) {
alert(item.gold);
}
is missing the ending ');'
which is why nothing is being alerted in your fiddle.
Related
I'm new to JavaScript , I have a problem to get new array like
one array result
day = ['sday','mday','tday'];
val = [1,2,3]
when I use array push
var array = [];
$.each(resp.result, function(index, item) {
array.push(item.day);
array.push(item.val );
});
output :- ['sday',1,'mday',2,'tday',3];
but I need
output :- ['sday',1],['mday',2],['tday',3]
I have seen the answer by D.Seah in comment section, But we need answer in answer field also. use
array.push([item.day,item.val]);
I'm wondering how I can access each object in this json string via jquery.
The string returned looks like:
{"Appointments":["\/Date(1507238100000)\/"],"Sessions":[]}
I need access to both the Appointments object as well as the Sessions object, I can't seem to figure it out.
I tried to access the Appointments object by index like:
$.each(data, function (index, element) {
$.each(data, function (index, element) {
//alert(JSON.stringify(element, null, 4));
alert(element.Appointments[index]);
});
//value = new Date(parseInt(element.Appointments.substr(6)));
//var rowContent = "<tr><td>" + value + "</td></tr>";
//$('#appointmentsTable tbody').append(rowContent);
});
This does not work however, thoughts?
You don't have to access element by element.Appointments[index] when you are looping though an array by $.each.
For example
var data = {"Appointments":["\/Date(1507238100000)\/"],"Sessions":[]};
To loop though object in data.Appointments, you simply do this
$.each(data.Appointments, function(index, element){
console.log(element);
});
To loop though object in data.Sessions, you simply do this
$.each(data.Sessions, function(index, element){
console.log(element);
});
For more example about $.each, please refer to JQuery API Documentation here.
You don't actually need jquery for this at all.
You could use plain javascript. If your project uses ES6, you could write it as:
// extract appointments and sessions from data
let { Appointments, Sessions } = data
// iterate over appointments
Appointments.forEach((appointment, index) => { console.log(appointment) })
// iterate over sessions
Sessions.forEach((session, index) => { console.log(session) })
Basically you don't really need index inside your iteration callback - you can directly access the elements you are iterating over instead. The same would apply to your jquery function as well.
If you prefer to use jQuery, your code could be rewritten as:
$.each(data.Appointments, (index, elem) => alert(elem))
I have many label and each of them has same class.My Label contains some information, which I need to read. How to read label attributes in Jquery. So far I could get object using $ but unable to get any value from its property.I need to get values for Id,Text, and title. Please help me to get those values .
$(".tagLabel").each(function (i, obj) {
var lableId = ?? // what I need to do with obj here to get it
var labelText=??
var lableTitle=??
});
Please try this:
$(".tagLabel").each(function (i, obj) {
var lableId = obj.id;
var labelText= $(obj).text();
var lableTitle= $(obj).attr('title');
});
Please note that you have to wait until your page is fully loaded, wrap your code with:
$(function() {
//Page fully loaded
//Put you code here
});
little confused, i have a .each function which displays all results from JSON when i use console.log but when i try to output using .html() it only shows one? any reason why?
code:
$(document).ready(function(){
$.get('functions/ListOrders.php', function(xml){
var newOrders = $.xml2json(xml);
$.each(newOrders.ListOrdersResult.Orders.Order, function(index, value) {
//console.log(value.AmazonOrderId);
$('#orderAmount').html("<b>Order Total:</b><br>" + index + "<br><br>");
$('#orderListing').html("<b>Order Listing:</b><br>" + value.AmazonOrderId);
});
});
});
Thanks
You getting only one result because in your loop you override existing value. Basically you override html value. If you use append instead it will add values to your existing elements with each loop iteration.
$(document).ready(function(){
$.get('functions/ListOrders.php', function(xml){
var newOrders = $.xml2json(xml);
$.each(newOrders.ListOrdersResult.Orders.Order, function(index, value) {
$('#orderAmount').append("<b>Order Total:</b><br>" + index + "<br><br>");
$('#orderListing').append("<b>Order Listing:</b><br>" + value.AmazonOrderId);
});
});
});
I want to
Get Text From Classes with class .pick and populate them into a dropdown #pingList
1) my Variable picker returns a long string, so I assume I need to create an array
2) var array I want the result to be ['x','y','z'] as I assume this is what I need in the next step.
3) I then want to add this to the dropdown with the text and val set.
I am pretty sure all I am missing is the array part. Looking for some help.
My Jquery Code and Live Demo http://jsfiddle.net/UUY5Z/1/
// Get text from Pick CLass
var picker = $('.pick').text();
// Make an Array from string result above
var array = //??
// Add this to the dropdown
$.each(array, function (val, text) {
$('#pingList').append($('<option></option>').val(val).html(text));
});
.text() method returns textContent of all of the selected elements as one string, you can use .map() method instead which returns an array:
var picker = $('.pick').map(function(i, elem) {
return "<option value='"+i+"'>" +
(elem.textContent || elem.innerText) + // == $(elem).text()
"</option>";
}).get(); // array of options (string)
$('#pingList').append(picker);
http://jsfiddle.net/JJsRd/
Here an other solution , using $.each() :
$.each($('.pick'),function(i, elem){
$('#pingList').append( "<option value='"+i+"'>"+ $(elem).text() +"</option>");
});
DEMO HERE
$('.pick').each(function(){
$('#pinglist').append(""+$(this).text()+"");
});
This should work for Above Case.
http://jsfiddle.net/sushilbharwani/uNpND/
I have updated in your demo page.. #http://jsfiddle.net/UUY5Z/7/
$(".pick").each(function(){
var val = $(this).text();
$('<option>').val(val).text(val).appendTo('#pingList');
});
You can achieve the same like this.
No need to make an array.
$.each($('.pick'), function (val, text) {
$('#pingList').append($('<option></option>').val($(this).text()).html($(this).text()));
});
JSFiddle For Same http://jsfiddle.net/sushilbharwani/uNpND/