Reputation: 567
I'm building a live price quote form with jQuery, using a series of select menus. I've come up with the code below, which grabs the default values from each select menu and adds them together:
$(document).ready(function(){
$('select > option:selected').each(function() {
var value = $(this).attr('label');
total = parseFloat(total) + parseFloat(value);
total = total.toFixed(2);
});
printTotal(total); // prints the total price
});
The only problem is that this only works when the page loads. I'd like the price to be updated each time a new value is selected in any of the select menus (there are 6).
I tried adding $("select").change(function () { ... } with a trigger (as shown in the example code here) but that adds up all of the values for each of the select menus (i.e., the total is 6x what it should be).
I've searched the docs but can't figure which event to use. Can anyone help?
HTML sample if it helps:
<select id="colors">
<option label="25.00" value="XYZ">1 color</option>
<option label="50.50" value="ABC">2 colors</option>
<option label="75.75" value="MNO">3 colors</option>
</select>
Upvotes: 1
Views: 2580
Reputation: 567
Matt, I think you triggered something in my mind, because I figured it out -- at least, it works so far.
Here is the code that does it:
$(document).ready(function(){
$('select').change(function() {
var total = 0;
$('select > option:selected').each(function() {
var value = $(this).attr('label');
total = parseFloat(total) + parseFloat(value);
total = total.toFixed(2);
});
printTotal(total);
});
});
It came down to placement of the var total = 0 piece, which has to be reset each time a new selection is made.
Upvotes: 1
Reputation: 83279
When testing within the change
call, you need to make sure that you search option
s within the context of the select
element that you clicked on.
$('select').change(function() {
var total = 0;
// note the second parameter passed to the $() function below
$('option:selected', $(this)).each(function() {
var value = $(this).attr('label');
total += parseFloat(value).toFixed(2);
});
printTotal(total);
});
Upvotes: 0