Reputation: 55
i am new with jQuery.. i have a table with a number of boxes in it. I want to grab all the select boxes in the table and loop through them..
I am trying to create a function that does this and it looks like this:
function calculatePercentageTotal(tableName) {
var total = 0;
for (i = 0; i <= $("#" + tableName + ' select').length; i++) {
total += parseInt($("#" + tableName + ' select')[i].val());
}
return total;
}
It's not working though.. any ideas? thanks!
Upvotes: 1
Views: 11819
Reputation: 103
Just use a selector to get the elements. I'm not sure which elements you are looking for. If what you are trying to do is to sum the values of the selected items in all the selects(dropdowns) then you can use this:
var mysum = 0;
$("#" + tableName.id + ' select').each(function(){
mysum += $(this).val() * 1;
});
alert("mysum = " + mysum.toString);
// Why **"$(this).val() * 1"** - .val() will return a string with the value selected
// * 1 will make it numeric.
Upvotes: 0
Reputation: 6903
$(document).ready(function(){
var total =0;
$("#calculatebtn").click( function(e){
$("select").each(function(){
total += parseInt($(this).val());
});
alert("total=" + total);
});
});
You need a button with id='calculatebtn'
Upvotes: 0
Reputation: 4079
this should do it:
function calculatePercentageTotal(tableName) {
var total=0;
$('#'+tableName+' select').each(function(){
total+= +($(this).val());
});
return total;
}
Upvotes: 8