jquery calculate value of selected option ID with duplicate selects
I wasn't even sure how to title this right.
I have a page that needs to add the total of multiple selects and display the total anytime a select is changed. All of the selects are named the same and the value of the options are in the ID of the option. Everything I've tried so far has failed prett开发者_如何学运维y terribly. Thanks.
example:
<select name="options">
<option ID="2.2" value="uid" selected>Option 1</option>
<option ID="1.8" value="uid">Option 2</option>
<option ID="3" value="uid">Option 3</option>
</select>
<select name="options">
<option ID="2.2" value="uid">Option 1</option>
<option ID="1.8" value="uid" selected>Option 2</option>
<option ID="3" value="uid">Option 3</option>
</select>
<div id="total">Total: 4</div>
Here's a function version in jsFiddle:
http://jsfiddle.net/shaneblake/BBhnZ/
HTML:
<select name="options">
<option data-value="2.2" value="uid" selected>Option 1</option>
<option data-value="1.8" value="uid">Option 2</option>
<option data-value="3" value="uid">Option 3</option>
</select>
<select name="options">
<option data-value="2.2" value="uid">Option 1</option>
<option data-value="1.8" value="uid" selected>Option 2</option>
<option data-value="3" value="uid">Option 3</option>
</select>
<div id="total">Total: 4</div>
JavaScript:
$(function() {
$("select[name='options']").change(function() { updateTotal(); });
updateTotal();
});
function updateTotal() {
var newTotal = 0;
$("select[name='options'] option:selected").each(function() {
newTotal += parseFloat($(this).data('value'));
});
$("#total").text("Total: " + newTotal);
}
You could do
var selects = $("select[name=options]");
selects.bind("change", recalculateSelectTotals);
function recalculateSelectTotals() {
var total = 0;
selects.find("option:selected").each(function () {
total += Number(this.id);
});
$("#total").text("Total: " + total);
}
However, you should use value
for values, and save ID for identifiers. Two selects with the same name is also invalid markup.
1: ID's cannot start with numbers.
2: You cannot have multiple items with the same ID
3: Give your select's classes or ID's so you can read their values $('#selectID').val()
精彩评论