Robert Robert - 1 year ago 54
jQuery Question

selected options sum using js

I have some selectors , all selectors have some options with some values , how to sum all values of selected options and also I want to attach the sum to a input field?

<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>


I have tried like,

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

Answer Source

You can try something like this

$("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" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download