I have a form that asks for addresses. After each address, we ask how long the person has lived in that address, with <select>
dropdowns for Years and Months.
I have a jQuery event each time the <select>
is changed:
var prev_addresses = 0;
$('select.months, select.years').change(function() {
// Calculate total months
var months = $('select.months').val();
var years = $('select.years').val();
var total_months = parseInt(months) + parseInt(years*12); // We parseInt() to avoid concatenation
console.log('Total months: '+total_months);
if(total_months < 12) {
// Find the next div.hidden-address
prev_addresses = prev_addresses+1;
console.log('Number of previous addresses: '+prev_addresses);
console.log('');
$('div.hidden-address').clone(true).appendTo('#previous-addresses').slideToggle();
}
});
I want this to keep on happening all the while a person has less than 12 months of addresses. However after the first time the event fires, every time a <select>
is updated the console just logs the first set of values (开发者_如何学Gofrom the original Year and Month selects, even though there are now multiple ones).
I want to total up the values of every <select>
element on a page, even after more are added dynamically. How can I do this?
Hope that makes sense, I'm happy to clarify if you need further details.
Thanks,
Jack
Loop through all select boxes, and add the value to a variable, something like this:
var totalMonths = 0;
$('select.months').each(function () {
totalMonths += $(this).val();
});
$('select.years').each(function () {
totalMonths += 12 * $(this).val();
});
精彩评论