如何在JQuery中找到具有多个答案的变量之和?

时间:2013-08-09 16:27:52

标签: jquery arrays variables

我正在尝试根据用户想要购买的门票数量来显示和显示门票价格。当我运行我的代码时,它完全符合我的要求,但第二个数字会覆盖第一个,如何将它们一起添加?

HTML:

     <ul id="tickets" class="clearfix registration-form"> 
            <li class="clearfix">
                <input type="hidden" id="ticket-price" value="90">
                <input class="short-input alpha number-tickets" type="number" placeholder="0" rel="#ticket-price">
                <label>Number of Tickets ($90 each)<p>This is some further information about tickets, and this can be as much information as you want it to be!</p></label>
            </li>
            <li class="clearfix">
                 <input type="hidden" id="ticket-price_2" value="35">
                 <input class="short-input alpha number-tickets" type="number" placeholder="0" rel="#ticket-price_2">
                 <label>Number of Tickets ($35 each)<p>This is some further information about tickets, and this can be as much information as you want it to be!</p></label>
            </li>
            <li class="tickets-total">
                 <label>Current Total = $</label>
                 <input id="ticketsTotal" type="number" placeholder="0.00" readonly="true">
            </li>
    </ul>

Javascript:

    $('input.number-tickets').keyup(function() {
    $('#tickets li input[type=number]')
            .not('#tickets li.tickets-total input[type=number]')
            .each(function(i, data) {
                var total = 0;
                var priceTotal = $(this).val() * $($(this).attr('rel')).val();

                for (var i=0; i < priceTotal.length; i++) {
                     total += priceTotal[i] << 0;
               }

               $('input#ticketsTotal').val(total);
    })
});

由于

3 个答案:

答案 0 :(得分:3)

您需要在 $。每个循环之外声明总变量(计数器)。正如您现在所做的那样,每次循环运行时都将变量设置为0.

var total = 0;
$('#tickets li input[type=number]')
    .not('#tickets li.tickets-total input[type=number]')
    .each(function (i, data) {
    var priceTotal = $(this).val() * $($(this).attr('rel')).val();

    for (var i = 0; i < priceTotal.length; i++) {
        total += priceTotal[i] << 0;
    }

    $('input#ticketsTotal').val(total);
});

答案 1 :(得分:2)

$('input.number-tickets').keyup(function () {
    var total = 0;
    $('#tickets li input[type=number]')
        .not('#tickets li.tickets-total input[type=number]')
        .each(function (i, data) {
        var priceTotal = $(this).val() * $($(this).attr('rel')).val();

        for (var i = 0; i < priceTotal.length; i++) {
            total += priceTotal[i] << 0;
        }

        $('input#ticketsTotal').val(total);
    })
});

答案 2 :(得分:0)

你应该使用像

这样的旧值
$('input#ticketsTotal').val(parseInt($('input#ticketsTotal').val()) + total);