2015-03-20 3 views
0

У меня есть таблица номеров счетов, даты и итоговые суммы. Я хотел бы, чтобы выбранная сумма возвращалась в jQuery в переменной. В настоящее время PHP генерирует таблицу, поэтому, если она помогает добавлять уникальные идентификаторы к входам или изменять вывод HTML, это совсем не проблема.Ячейки сумм jQuery на основе соответствующего выбора флажка

Я провел некоторое исследование в нем, и, похоже, существует миллион способов достижения того, что я ищу; от конкатенации идентификаторов и цен на входе (стиль «5: 75,97»), а затем разделения их на манипуляции, вплоть до поиска по HTML для ближайшего флажка и добавления чисел таким образом. Кажется, все сработают; просто любопытно узнать, что такое идеальное решение.

Например, если счет-фактура 5 и 12 были выбраны, переменная будет равна 106.94

Любая помощь будет высоко оценили.

<table> 
    <tr> 
     <th>Invoice #</th> 
     <th>Date</th> 
     <th>Balance</th> 
    </tr> 
    <tr> 
     <td><input type="checkbox" name="Invoices[]" value="" /> Invoice 5 </td> 
     <td>2015-03-03</td> 
     <td>75.97</td> 
    </tr> 
    <tr> 
     <td><input type="checkbox" name="Invoices[]" value="" /> Invoice 8</td> 
     <td>2015-03-07</td> 
     <td>35.97</td> 
    </tr> 
    <tr> 
     <td><input type="checkbox" name="Invoices[]" value="" /> Invoice 12</td> 
     <td>2015-03-01</td> 
     <td>30.97</td> 
    </tr> 
</table> 

ответ

0

Вы могли бы сделать что-то вроде этого: fiddle

var sum = 0; 
$('input').click(function() { 

    if ($(this).is(':checked')) { 
     var price = $('.price'); 
     var add = ($(this).closest('tr').find(price).html()); 
     add = parseFloat(add).toFixed(2); 
     sum += +add; 
     console.log(sum); 
    } else if (!$(this).is(':checked')) { 
     var price = $('.price'); 
     var add = ($(this).closest('tr').find(price).html()); 
     add = parseFloat(add).toFixed(2); 
     sum -= +add; 
     console.log(sum); 
    } 

}); 
0

Вот как я бы это сделать:

var totalInvoice; 
    $('input').on('change', function(){ 
     totalInvoice = 0; 
     $('input:checked').each(function(){ 
      totalInvoice += parseFloat($(this).parent().siblings('td:nth-last-child(1)').text()); 
     }); 
     console.log(totalInvoice); 
    }) 

Имейте в виду, что это будет лучше, если вы указать вход, что ваш ссылаясь на класс или что-то в этом роде.

0

Я хотел бы предложить:

// finding the inputs of type=checkbox, binding a change 
// event-handler: 
$('table input[type="checkbox"]').on('change', function() { 
    // finding the closest <table>: 
    var table = $(this).closest('table'), 
    // finding the checked checkboxes inside of that <table>: 
    checked = table.find('input[type=checkbox]:checked'), 
    // getting the last <td> from the <tr> that contains the 
    // checked checkboxes: 
    prices = checked.closest('tr').find('td:last-child'), 
    // iterating over those <td> elements: 
    sum = prices.map(function() { 
     // creating a map containing the found prices, if the 
     // trimmed text is not a number we return 0: 
     return parseFloat(this.textContent.trim(), 10) || 0; 
    // converting the map to an array, and passing it 
    // to the reduce method: 
    }).get().reduce(function(a, b) { 
     // summing the current value (a) with new value (b): 
     return a + b; 
    }); 
    // setting the text of the element whose id="result": 
    $('#result').text(sum); 
// triggering the change event (in the case of any 
// checkboxes being checked on page-load: 
}).change(); 

$('table input[type="checkbox"]').on('change', function() { 
 
    var table = $(this).closest('table'), 
 
    checked = table.find('input[type=checkbox]:checked'), 
 
    prices = checked.closest('tr').find('td:last-child'), 
 
    sum = prices.map(function() { 
 
     return parseFloat(this.textContent.trim(), 10) || 0; 
 
    }).get().reduce(function(a, b) { 
 
     return a + b; 
 
    }); 
 
    $('#result').text(sum); 
 
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tbody> 
 
    <tr> 
 
     <th>Invoice #</th> 
 
     <th>Date</th> 
 
     <th>Balance</th> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     <input type="checkbox" name="Invoices[]" value="" />Invoice 5</td> 
 
     <td>2015-03-03</td> 
 
     <td>75.97</td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     <input type="checkbox" name="Invoices[]" value="" />Invoice 8</td> 
 
     <td>2015-03-07</td> 
 
     <td>35.97</td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     <input type="checkbox" name="Invoices[]" value="" />Invoice 12</td> 
 
     <td>2015-03-01</td> 
 
     <td>30.97</td> 
 
    </tr> 
 
    </tbody> 
 
</table> 
 

 
<div id="result"></div>

Ссылки:

Смежные вопросы