I have looked for answers on here and have not found anything that directly can help me so I am going to ask here. I have a form with multiple select boxes:
Try this, it will work for dynamically created select elements too.
$(document).on('change', 'select[name="acabados[]"]', function(){
var total = 0;
$('select[name="acabados[]"]').each(function(){
total += parseInt($(this).val());
});
});
total
var will contain the total of all the select elements selected value.
$(function () {
var $select = $('select');
$select.on('change', function () {
var output = 0;
for (var i = 0, len = $select.length; i < len; i++) {
output += parseInt($select.eq(i).val());
}
//the `output` variable now contains the addition of all the values from the `acabados[]` select elements
});
});
Here is a demo: http://jsfiddle.net/aPXXA/1/
You can change var $select = $('select');
to var $select = $('[name="acabados[]"]');
to only select the select
elements with the acabados[]
name attribute.
If you want to retrieve the values in PHP, you can just use $_POST['acabados']
and it will contain all the values selected in each menu. See a demo. As long as you include the []
after the name, it will compound all the values for any element with that name into a single array. You can even mix select menus, inputs, and textareas together!
Why not just give them different id's and do the count in jquery/javascript. Alternatively give them all the same class, and do .each() to grab the values in all of them.