jquery: grab the values from multiple select menus each time a new option is chosen

StackOverflow https://stackoverflow.com/questions/1564635

  •  21-09-2019
  •  | 
  •  

문제

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>
도움이 되었습니까?

해결책

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.

다른 팁

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);
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top