jQuery update initial price on click on checkbox that has data-price attribute

北慕城南 提交于 2019-12-14 03:18:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!