我想从多个下拉菜单和复选框中计算总数。 此代码适用于select:选项下拉列表,但我的问题是添加了检查输入。
以下是我使用的代码:“只需要它来计算选中的框以及所选的下拉列表”
$(window).load(function() {
var basePrice = 0;
$(".calculate").change(function() {
newPrice = basePrice;
$(".calculate option:selected").each(function() {
newPrice += parseFloat($(this).data('price'));
console.log(typeof newPrice);
});
newPrice = newPrice.toFixed(2);
$("#item-price").html(newPrice);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="type2" name="service" class="calculate">
<option data-price="0" value="">-- Select --</option>
<option data-price="100" value="kite1">wash</option>
<option data-price="150" value="kite1">wash and dry</option>
<option data-price="1000" value="kite2">repair</option>
</select>
<input type="checkbox" class="calculate" data-price="300" name="vehicle" value="Bike">roof
<input type="checkbox" class="calculate" data-price="200" name="vehicle" value="rims">rims
<span id="item-price">0</span>
答案 0 :(得分:1)
请参阅内联评论以获得解释:
// Instead of window.load, you can get your function to run earlier
// by setting it up for when the DOM is ready. As long as the function
// doesn't rely on externally loaded content, this is generally a
// better idea because the page becomes interactive quicker.
// Do that by just passing your callback function to JQuery:
$(function(){
// You need to run the function when the select gets changed but also when the
// checkboxes get clicked. Now, you could use a simple selector to get references
// to all the elements in question here, but this could cause other elements that
// are not related to this operation to be erroneously included. It's better to
// be specific with selectors so that the code can scale.
// Also, modern JQuery recommends the use of the "on" method for event binding.
$("select.calculate").on("change", calc);
$("input[type=checkbox].calculate").on("click", calc);
function calc() {
var basePrice = 0;
newPrice = basePrice;
// You need to loop over, not only the selected option, but also the checked checboxes
$("select.calculate option:selected, input[type=checkbox].calculate:checked").each(function () {
newPrice += parseInt($(this).data('price'), 10);
});
newPrice = newPrice.toFixed(2);
$("#item-price").html(newPrice);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="type2" name="service" class="calculate" >
<option data-price="0" value="">-- Select --</option>
<option data-price="100" value="kite1">wash</option>
<option data-price="150" value="kite1">wash and dry</option>
<option data-price="1000" value="kite2">repair</option>
</select>
<input type="checkbox" class="calculate" data-price="300" name="vehicle" value="Bike">roof
<input type="checkbox" class="calculate" data-price="200" name="vehicle" value="rims">rims
<span id="item-price">0</span>
&#13;