'How to sum up values from specific dropdown only
I have a dropdown as shown below. I need to sum up the values of all the dropdowns that have a specific name as indicated.
jQuery(function () {
$('select').change(function(){
var sum = 0;
$('select :selected').each(function() {
sum += Number($(this).val());
});
$("#sum").html(sum);
});
});
<h6>Nunber <a id="sum">0</a></h6>
<div class="form-group mb-2">
<label>Select Repetition</label> <br>
<select id="ddlViewBy" name="repetition[]" >
<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>
Using the code below, I am able to duplicate the dropdown above into as many dropdowns as I need.
<script>
$(document).ready(function(){
$(document).on('click', '.remove-btn', function() {
$(this).closest('.main-form').remove();
});
$(document).on("click", ".add-more-form", function() {
$('.paste-new-forms').append('
<label>Select Repetition</label> <br>\
<select id="ddlViewBy" name="repetition[]">\
<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>\
<button onClick="onUnClick()" type="button" class="btn-danger">X</button>\
');
});
});
</script>
Problem:
The code appears to sum everything including values from other dropdowns in my form. I am interested in the dropdowns with the name repetition[]
only.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|