views:

303

answers:

2

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>
A: 

When testing within the change call, you need to make sure that you search options 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);
});
Matt Huggins
Thanks for the response Matt. That doesn't quite do it, since the total is reset to the value of the selected option each time a new selection is made. If I move "var total = 0" outside of the change function, then each new selection keeps adding onto the total, instead of replacing the last selection. I hope that makes sense...I also had to keep my addition the same, broken onto 2 lines, because otherwise "total" kept acting like a string.
Ryan
My placement of the 'var total = 0;' appears to be in the same location as your updated code from your comment, if I'm not mistaken. As for why you split your addition into 2 lines, that makes sense since toFixed() returns a string, meaning the value of total will be a string each time in the loop. Glad I could help steer you in the right direction! :)
Matt Huggins
A: 

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.

Ryan