如何总结的使用jQuery选择的选项值?(how to sum values of selected

2019-07-03 21:46发布

你好,我有3种选择,所有的选择有一定价值的一些选项,如何总结所选选项的所有值?

<select name='anch1'>
 <option value='10'>10 ++</option>
 <option value='20'>20 ++</option>
 <option value='30'>30 ++</option>
 <option value='40'>40 ++</option>
 <option value='50'>50 ++</option>
</select>

<select name='anch2'>
 <option value='10'>10 ++</option>
 <option value='20'>20 ++</option>
 <option value='30'>30 ++</option>
 <option value='40'>40 ++</option>
 <option value='50'>50 ++</option>
</select>

<select name='anch3'>
 <option value='10'>10 ++</option>
 <option value='20'>20 ++</option>
 <option value='30'>30 ++</option>
 <option value='40'>40 ++</option>
 <option value='50'>50 ++</option>
</select>

<div>SUM OF SELECTED OPTIONS</div>

Answer 1:

$('select').change(function(){
    var sum = 0;
    $('select :selected').each(function() {
        sum += Number($(this).val());
    });
     $("#sum").html(sum);
});

http://jsfiddle.net/8mnQR/1/



Answer 2:

   var sum =  parseInt($('select[name="anch1"]').val()) +parseInt($('select[name="anch2"]').val()) +parseInt($('select[name="anch3"]').val() )

你可以这样做



文章来源: how to sum values of selected options using jquery?