jQuery更新初始价格点击具有data-price属性的复选框

时间:2014-01-29 12:40:09

标签: jquery checkbox custom-data-attribute

我想点击Initial Price点击checkbox时有data-price值,我尝试做到但到目前为止没有运气,所以如果你建议我会非常感激哪里我错了。所以这是代码;

http://jsfiddle.net/2M4Gr/1/

HTML标记:

<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代码: (不确定我是否正确行事)

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 个答案:

答案 0 :(得分:-1)

此处更新了代码: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);