简体   繁体   中英

sum multiple values from inputs and selects in form

i need to sum the values from multiple SELECTS and INPUTS, this is what i have so far:

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>

JQUERY

$('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');
});

As you can notice it only sum the value from first select i need it too sum from all the selects.

DEMO: http://jsfiddle.net/B9ufP/

Try this:
(I simplified a bit your code)

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

Demo here

If you want to be fancy, you can also use Array.prototype.reduce to sum up the values.

Note that if you have decimals, use parseFloat .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM