I have a table containing a variable number of columns. I wrote a function to iterate through each cell in each row to do the following:
Here's my code:
function addPieCharts() {
var htmlPre = "<span class='inlinesparkline' values='";
var htmlPost = "'></span>"
var colors = ["red", "blue"];
$("#MarketsTable tr").each(function () {
$('td').each(function () {
var value = $(this).find(":input").val();
var values = 100 - value + ', ' + value;
if (value > 0) {
$(this).append(htmlPre + values + htmlPost);
}
})
})
$('.inlinesparkline').sparkline('html', { type: 'pie', sliceColors: colors });
}
Steps 1-3 are basically working as described. When this runs the pie charts are added to the correct cells displaying the correct values. My problem is that I'm expecting just one pie chart per cell where there exists an input. However, I have n pie charts per cell where n is equal to the number of columns in the table. I suspect I'm using jQuery's each() method incorrectly. Can someone tell me what I've done wrong?
In short, if we want to loop over a simple array, complex JSON object, or over HTML tag, i.e., loop over table row tr or list tag, then using each() method we can achieve all. For Reference: jQuery. each()
When you select td
pass the context as tr(this
) so that it will look for td
only in the current tr
. Try this.
$("#MarketsTable tr").each(function () {
$('td', this).each(function () {
var value = $(this).find(":input").val();
var values = 100 - value + ', ' + value;
if (value > 0) {
$(this).append(htmlPre + values + htmlPost);
}
})
})
Here is how I would modify you code:
#MarketsTable td:has(:input)
: this selector will find TD that has at leats one INPUT element inside
no need to store your parts of html in variables IMO, just create the element when needed and append it to the TD
Here's the modified code:
function addPieCharts() {
var colors = ["red", "blue"];
// directly select the TD with an INPUT element inside
$('#MarketsTable td:has(:input)').each(function() {
var value = $(this).find(":input").val();
if (value > 0) {
// only make the values string if necessary, when value > 0
var valStr = (100 - value).toString() + ', ' + value;
// create your span tag and append it to 'this' (the TD in this case)
$('<span class="inlinesparkline" values="' + valStr + '"></span>').appendTo(this);
}
});
$('.inlinesparkline').sparkline('html', {
type: 'pie',
sliceColors: colors
});
}
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With