Reputation: 10068
How do you use the jquery onchange function to update an input field so that it keeps a running total?
e.g. I have the following dropdown list options:
<select name="select" id="set1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="select" id="set2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" name="total" id="total" value="" />
When a user select an option from the two dropdowns above, I need the total of the two selected options to be displayed in the input field. This would need to dynamically change each time a different option was selected. How can you achieve this with jquery?
Upvotes: 0
Views: 1167
Reputation: 26360
Works with any number of 'select' :
$select = $('select.numberSelect');
$select.on('change', function(){
var total = 0;
$select.each(function(e){
total += parseInt($(this).val()); // or parseInt(e.currentTarget.value)
})
$('#total').val(total);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class='numberSelect'>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select class='numberSelect'>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select class='numberSelect'>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input type="text" id="total" value="3" />
Edit : Removed a lot of useless stuff (names, IDs, value="", ...) and added a third select for demonstration purposes.
Edit 2 : added a class to target the specific 'select' elements, and not others in the DOM.
Upvotes: 0
Reputation: 53
You could do the following:
$('#set1, #set2').on('change', function (e) {
var first = $('#set1').val();
var second = $('#set2').val();
$('#total').val( parseInt(first) + parseInt(second) );
});
Is this what you want? JSFiddle (Demo)
Upvotes: 1
Reputation: 7518
Works with your html. It could be improved if you have a dynamic # of selects.
$(document).on("change","#set1,#set2", function() {
var sum = parseInt($("#set1").val()) + parseInt($("#set2").val());
$("#total").val(sum);
});
Upvotes: 0
Reputation: 4821
$('[name=select]').change(function () {
$('#total').val(Number($('#set1').val()) + Number($('#set2').val()));
});
This gets the currently selected values from #set1
and #set2
, converts them to numbers, then sets the value of the #total
element.
To convert strings to numbers, you can use the Number()
method like I have, for readability. You can also do $('#set1').val() - 0
, which isn't very understandable, but is significantly faster. To see a comparison of all the methods of converting string to number and their performance, check out: http://jsperf.com/convert-string-to-number-techniques/2
Upvotes: 0