Reputation: 1322
I'm trying to add the sum of my drop down list values to give a total value at the bottom...
this is my javascript:
<script src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$("#overtimehours").change(function() {
var total = 0;
$.each($(".overtimehours") ,function() {
total += parseInt($(this).val());
});
$("#sum").val(total)
});
</script>
heres my php:
print "<td><div align=\"center\"><select name=\"overtimehours["; echo $transnum; print "]\"><option value=\"$ot_hours\">$ot_hours</option>"; overtimehours_list();
print "</select></div></td>\n";
print "<td><div align=\"center\"><b><input id=\"sum\" type=\"text\"/></b></td></tr>\n"; //add up OT hrs
RESOLVED :: HERES THE JSFIDDLE DEMO FIX: http://jsfiddle.net/st8Y3/6/
Upvotes: 0
Views: 1433
Reputation: 40461
Keep your PHP the same and do this...
$(document).on('change', 'select[name="overtimehours"]', function(){
var total = 0;
$('select[name="overtimehours"]').each(function() {
total += parseInt($(this).val());
});
$('#sum').val(total)
});
EDIT:
PHP:
print "<td><div align=\"center\"><select class=\"overtimehours\" name=\"overtimehours["; echo $transnum; print "]\"><option value=\"$ot_hours\">$ot_hours</option>"; overtimehours_list();
print "</select></div></td>\n";
print "<td><div align=\"center\"><b><input id=\"sum\" type=\"text\"/></b></td></tr>\n"; //add up OT hrs
JAVASCRIPT:
$(document).on('change', '.overtimehours', function(){
var total = 0;
$('.overtimehours').each(function() {
total += parseInt($(this).val());
});
$('#sum').val(total)
});
DEMO: http://jsfiddle.net/dirtyd77/st8Y3/3/
Upvotes: 1
Reputation: 3818
Add the class overtimeshours
to your select declaration.
print "<td><div align=\"center\"><select class=\"overtimehours\" name=\"overtimehours["; echo $transnum; print "]\"><option value=\"$ot_hours\">$ot_hours</option>"; overtimehours_list();
Change your jQuery to:
$(".overtimehours").change(function() {
var total = 0;
$.each($(".overtimehours") ,function() {
total += parseInt($(this).val());
});
$("#sum").val(total)
});
More on Class Selectors
Upvotes: 0
Reputation: 71384
You refer to overtimehours
as both an id and a class name, yet your input has neither the id or class name. I would suggest add a class called overtimehours
to each input that is to be calculated and the change your selector to $('.overtimehours')
instead of $('#overtimehours')
.
Upvotes: 1