Reputation: 147
I have some selectors, and they all have some options with some values. How do I sum all values of selected options and also 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 this:
$('select').change(function(){
var sum = 0;
$('selected').each(function() {
sum += Number($(this).val());
});
$("#roomnumber").val(sum);
});
Upvotes: 1
Views: 2664
Reputation: 436
here is JSfiddle link : https://jsfiddle.net/fesi39/apb8as1h/
$('select').change(function(){
var sum = 0;
$('.selecter').find(":selected").each(function(){
sum = sum + parseInt($(this).val());
$('span').html(sum);
});
});
<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>
Upvotes: 0
Reputation: 337560
Your logic is almost correct, the issue is simply that selected
is not a valid selector. To retrieve the selected option
elements use option:selected
instead:
$('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" />
Upvotes: 1
Reputation: 199
Give same name to each of your select tag (eg. 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);
Upvotes: 1
Reputation: 27041
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" />
Upvotes: 2