Reputation: 201
I'm using the following code to add/remove a price form a span (quote-price) when a button and select menus are selected. The following code works great for the buttons and for when I am using just one select menu, however when I use multiple select menus, it fails. Does anyone know how I can adjust the below code to work with multiple select menus?
$(document).ready(function() {
function updateTotal() {
var total = 0;
$('button.selected').each(function() {
total += parseFloat($(this).val());
});
total += parseFloat($('select').val());
$('span.quote-price').text("£" + total.toFixed(2));
}
$('button').click(function() {
$(this).toggleClass('selected');
updateTotal();
});
$('select').change(updateTotal);
$('.reset').click(function() {
$('.selected').removeClass('selected');
$('select').val('0.00');
updateTotal();
});
});
Upvotes: 0
Views: 214
Reputation: 8578
You can just immitate the code you already have for the button. Instead of this:
total += parseFloat($('select').val());
..use this:
$('select').each(function() {
total += parseFloat($(this).val());
});
That will add the value for every select on the page to the variable total
. In case you just want some selects (you might have them for other reasons on your page), add a class (like price
for instance) to them, and change the selector to select.price
.
Upvotes: 1
Reputation: 11512
Try with following code:
$(document).ready(function() {
function updateTotal() {
var total = 0;
$('button.selected').each(function() {
total += parseFloat($(this).val());
});
$('select').each(function() {
total += parseFloat($(this).val());
});
$('span.quote-price').text("£" + total.toFixed(2));
}
$('button').click(function() {
$(this).toggleClass('selected');
updateTotal();
});
$('select').change(updateTotal);
$('.reset').click(function() {
$('.selected').removeClass('selected');
$('select').val('0.00');
updateTotal();
});
});
Instead of
total += parseFloat($('select').val());
I used
$('select').each(function() {
total += parseFloat($(this).val());
});
Upvotes: 0