求和来自输入的多个值,并在形式中进行选择

sum multiple values from inputs and selects in form

本文关键字:选择 行选 输入 求和      更新时间:2023-09-26

我需要将多个SELECTS和INPUTS的值相加,这就是我目前所拥有的:

HTML

<label>Item#1</label>
<select name="price[]" id="sel_1">
    <option value="">Options</option>
    <option value="4.00">Small</option>
    <option value="8.00">Medium</option>
</select>
<br>
<label>Item#2</label>
<select name="price[]">
    <option value="">Options</option>
    <option value="4.00">Small</option>
    <option value="8.00">Medium</option>
</select>
<br>
<label>Item#3</label>
<select name="price[]">
    <option value="">Options</option>
    <option value="4.00">Small</option>
    <option value="8.00">Medium</option>
</select>
<br>
<label>Item#4</label>
<input type="checkbox" value="1.00" id="price[3]" name="price[]">
<br>
<label>Item#5</label>
<input type="checkbox" value="2.00" id="price[3]" name="price[]">
<br>
<label>Item#6</label>
<input type="checkbox" value="3.00" id="price[3]" name="price[]">
<br> <span id="usertotal"> </span>

查询

$('input:checkbox').change(function () {
    var tot = 0;
    $('input:checkbox:checked').each(function () {
        tot += Number($(this).val());
    });
    tot += Number($('#sel_1').val());
    $('#usertotal').html(tot)
});
$('#sel_1').change(function () {
    $('input:checkbox').trigger('change');
});

正如你可以注意到的,它只对第一次选择的值求和,我需要它也对所有选择求和。

演示:http://jsfiddle.net/B9ufP/

试试这个:
(我简化了你的代码)

(function ($) {
    var $total = $('#usertotal');
    $('input,select:selected').on('change', function () {
        var tot = 0;
        $(':checked, select').each(function () {
            tot += ~~this.value;
        });
        $total.html(tot)
    });
}(jQuery))

演示此处

如果你想变得花哨,你也可以使用Array.prototype.reduce来汇总这些值。

请注意,如果您有小数,请使用parseFloat

var total = [].reduce.call($('select, :checkbox:checked'), function (pv, cv) {
    return parseFloat(pv.value) + parseFloat(cv.value);
});