问题
I want to update Initial Price
when click on checkbox
that has data-price
value, i try to done it but no luck so far, so it would be highly appreciable if you advise me where I'm wrong about it. So here is the code;
http://jsfiddle.net/2M4Gr/1/
HTML Markup:
<div class="price">$ <span>10.00</span></div>
<hr />
<form>
<label><input type="checkbox" name="Side Order" value="Side Order 1" />Side Order 1</label>
<label><input type="checkbox" name="Side Order" value="Side Order 2" />Side Order 2</label>
<label><input type="checkbox" name="Side Order" value="Side Order 3" />Side Order 3</label>
<label><input type="checkbox" name="Side Order" value="Side Order 4" />Side Order 4</label>
<label><input type="checkbox" name="Side Order" value="Side Order 5" />Side Order 5</label>
<label><input type="checkbox" name="Side Order" value="Side Order 6" data-price="5.00" />Side Order 6 (+ $5.00)</label>
<label><input type="checkbox" name="Side Order" value="Side Order 7" data-price="5.00" />Side Order 7 (+ $5.00)</label>
</form>
jQuery Code: (not sure either I'm doing it right way or not)
var $cbs = $('input');
function calcUsage() {
var total = $('.price span').text();
$cbs.each(function () {
if (this.checked) {
total += parseInt(this.value);
}
});
$('.price span').text(total);
}
function displayVals() {
calcUsage();
}
$("select").change(displayVals);
displayVals();
$cbs.click(calcUsage);
回答1:
Updated code here: http://jsfiddle.net/2M4Gr/2/
var $cbs = $('input');
function calcUsage() {
var total = parseInt($('.price span').text());
$cbs.each(function () {
var price = $(this).data("price");
if (this.checked && price) {
total += parseInt(price);
}
});
$('.price span').text(total);
}
function displayVals() { calcUsage(); }
$("select").change(displayVals);
displayVals();
$cbs.click(calcUsage);
来源:https://stackoverflow.com/questions/21431430/jquery-update-initial-price-on-click-on-checkbox-that-has-data-price-attribute