使用JS选择的选项总和

时间:2017-08-17 10:06:25

标签: javascript jquery

我有一些选择器,它们都有一些带有一些值的选项。如何对所选选项的所有值求和,并将总和附加到输入字段?

<select name='sel1'>
 <option value='40'>40 </option>
 <option value='50'>50 </option>
</select>

<select name='sel2'>
 <option value='10'>10 </option>
 <option value='20'>20 </option>
</select>

我试过这个:

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

4 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情

$("select[name^='sel']").change(function() {
  var s = $('select[name^="sel"] option:selected').map(function() {
    return this.value
  }).get()

  var sum = s.reduce((pv, cv) => {
    return pv + (parseFloat(cv) || 0);
  }, 0);

  $("#sum").val(sum)
})

$("select[name^='sel']").change(function() {
  var s = $('select[name^="sel"] option:selected').map(function() {
    return this.value
  }).get()

  var sum = s.reduce((pv, cv) => {
    return pv + (parseFloat(cv) || 0);
  }, 0);

  $("#sum").val(sum)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='sel1'>
 <option value='40'>40 </option>
 <option value='50'>50 </option>
</select>

<select name='sel2'>
 <option value='10'>10 </option>
 <option value='20'>20 </option>
 </select>

<input id="sum" />

答案 1 :(得分:1)

为每个选择标记指定相同的名称(例如,name =“s”)。

var arr = document.getElementsByName('s');
var sum = 0;
for(var i=0;i<arr.length;i++){
    sum+=parseInt(arr[i].value);
}
console.log(sum);

答案 2 :(得分:1)

您的逻辑几乎是正确的,问题只是selected不是有效的选择器。要检索选定的option元素,请改为使用option:selected

$('select').change(function() {
  var sum = 0;
  $('option:selected').each(function() {
    sum += parseInt($(this).val(), 10);
  });
  $("#roomnumber").val(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='sel1'>
 <option value='40'>40 </option>
 <option value='50'>50 </option>
</select>

<select name='sel2'>
 <option value='10'>10 </option>
 <option value='20'>20 </option>
</select>

<input id="roomnumber" type="text" />

答案 3 :(得分:0)

这里是JSfiddle链接:https://jsfiddle.net/fesi39/apb8as1h/

&#13;
&#13;
$('select').change(function(){
var sum = 0; 
$('.selecter').find(":selected").each(function(){
		sum = sum +  parseInt($(this).val());
    $('span').html(sum);
});
});
&#13;
<div class='selecter'>
<select name='sel1'>
 <option value='40'>40 </option>
 <option value='50'>50 </option>
</select>

<select name='sel2'>
 <option value='10'>10 </option>
 <option value='20'>20 </option>
</select>
<h2>result <span class='resultAppend'></span></h2>
</div>  

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;