如何获得每次更改的下拉值总和

时间:2018-01-05 12:44:43

标签: javascript

我想对每次更改的下拉值求和。我想总结选定的经验值。这是我的代码。请任何人帮助我

$(document).ready(function () {
    var selects = $('select[name^=exp_year]');
    selects.change(function () {
        var value = 0;
        selects.each(function () {
            value += +this.value;
        });
        alert(value);
        $('#dis').val(value);
    }).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="exp_year[]" id="exp_year" class="form-control">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option></select> 
<div id="dis"></div>

3 个答案:

答案 0 :(得分:0)

如果我理解正确,这就是您要搜索的内容:

<script>
$(document).ready(function () {
    var value = 0;
    $('#exp_year').change(function () {
        value += parseInt(this.value);
        alert(value);
        $('#dis').text(value);
    });
});
</script>

value事件之外初始化变量change

答案 1 :(得分:0)

您需要在var value = 0;上方定义var selects = $('select[name^=exp_year]');并将$('#dis').val(value);更改为$('#dis').text(value);

&#13;
&#13;
$(document).ready(function () {
    var value = 0;
    var selects = $('select[name^=exp_year]');
    selects.change(function () {
        
        selects.each(function () {
            value += +this.value;
        });
        alert(value);
        $('#dis').text(value);
    }).trigger('change');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="exp_year[]" id="exp_year" class="form-control">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option></select> 
<div id="dis"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

如果我正确理解了您的问题,那么您的代码就会出现几个问题。您在更改功能中有值变量,您需要将其置于外部,其次您设置$('#dis').val(value);而不是设置$('#dis').html(value);检查代码段

$(document).ready(function () {
    var value = 0;
    var selects = $('select[name^=exp_year]');
    selects.change(function () {

        selects.each(function () {
            value += +this.value;
        });
        alert(value);
        $('#dis').html(value);
    }).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="exp_year[]" id="exp_year" class="form-control">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option></select> 
<div id="dis"></div>