Reputation: 24305
I have a JSON object of data containing items and their sales listed by month. I'd like to list the item sales/month inside a DIV alongside other info about each item.
Here's my JSON object:
var my_object= [{"item_id":"11","month":"February","sales":"7"}, {"item_id":"4","month":"February","sales":"2"},{"item_id":"11","month":"March","sales":"1"},{"item_id":"4","month":"March","sales":"2"}]
here's how i'd like the final HTML to look:
<ul><li><button value="4">item_id_4</button><div>where the item_4 sales/month (i.e., 2,2) should go</div></li>
<li><button value="11">item_id_11</button><div>where the item_11 sales/month (i.e, 7,1) should go</div></li></ul>
lastly, here's my not yet correct jquery/javascript attempt to display the item counts/month.
$(function(){
$('button').each(function(){
var my_object = [{"item_id":"11","month":"February","sales":"7"}, {"item_id":"4","month":"February","sales":"2"},{"item_id":"11","month":"March","sales":"1"},{"item_id":"4","month":"March","sales":"2"}];
var button_value=$(this).val();
$.each(my_object, function(i,item){
if(item.item_id==button_value){
$('div').append(item.sales);
}
});
});
});
As it stands, this script displays the sales for both items in EACH div, i.e., 2,2,7,1 instead of just displaying 2,2 and 7,1 in their respective item_id_4 and item_id_11 divs separately. This makes it seem like the if statement is doing at least something right in that the "my_object" item sales are listed in the order of the button value and not as they are ordered in the "my_object".
I'm not sure whether the issue is with the each() functions, the IF statement, or maybe something else not mentioned here. Any help fixing this script would be greatly appreciated!
Upvotes: 0
Views: 777
Reputation: 2192
Your script seems to work fine except for the append line, where you tell jQuery to select all divs on the page and append your sales figures to them. Obviously that's not quite what you wanted. :)
Using your current HTML structure, changing that line to select the next div seems to work. (I've also saved the current button in $this.)
$this.next("div").append(item.sales);
Code here http://jsfiddle.net/meloncholy/ZhrZU/
Upvotes: 1
Reputation: 754715
Try the following
$(function(){
var my_object = [{"item_id":"11","month":"February","sales":"7"}, {"item_id":"4","month":"February","sales":"2"},{"item_id":"11","month":"March","sales":"1"},{"item_id":"4","month":"March","sales":"2"}];
for (var i in my_object) {
var cur = my_object[i];
$('button[value=' + cur.item_id + ']').each(function() {
var msg = 'Sales Month: ' + cur.month + ' Number: ' + cur.sales;
$(this).parent().append('<div>' + msg + '</div>');
});
}
});
I wasn't quite sure what you wanted the staring HTML to be but I assumed the following
<ul><li><button value="4"></button></li>
<li><button value="11"></button></li></ul>
Fiddle: http://jsfiddle.net/HdgmN/
Upvotes: 0