实时计算下拉列表

时间:2013-10-01 16:04:59

标签: jquery forms html-select

演示:http://jsfiddle.net/NaUAL/61/

<select name="one" id="one" >
            <option value="0" >Select *</option>
            <option value="3000" >Plan A</option>
            <option value="6000" >Plan B</option>
            <option value="9000" >Plan C</option>

        </select>

<br />

<select name="two" id="two">
        <option>Please choose from above</option>
</select>

<div id="total"></div>

需要在“总计”div中同时选择两个选项框...

3 个答案:

答案 0 :(得分:2)

$("#one,#two").change(function() {
    $('#total').text(parseInt($("#one").val()) + parseInt($("#two").val()))
});

检查我的小提琴here

答案 1 :(得分:1)

尝试

$("#one,#two").change(function(){
    var val1 = parseInt($('#one').val()) || 0, val2 = parseInt($('#two').val()) || 0;
    $('#total').text(val1 + val2)
})

演示:Fiddle

答案 2 :(得分:1)

DEMO

$('#two').change(function(){
    if(this.value != ''){
        $('#total').text(parseInt(this.value) + parseInt($("#one option:selected").val()));
    }
});

更改

second.html(html.join());

second.html(html.join()).change();

$("#one").change(function () {
    var first = $(this),
        second = $("#two"),
        key = first.val(),
        // instead of the original switch code
        vals = data[key] == undefined ? data.base : data[key],
        html = [];
    // create insert html before adding
    $.each(vals, function (i, val) {
        var v = val.split('_');
        html.push('<option value="' + v[1] + '">' + v[0] + '</option>')
    });
    // no need to empty the element before adding the new content
    second.html(html.join()).change(); //added .change()  here
});