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:
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