2016-01-14 1 views
3

Когда я нажимаю кнопку «Создать», мне нужно, чтобы значение поля #payment_reference генерировалось в соответствии с кодом. Я думаю, что код делает это в значительной степени ясно, что я хочу, чтобы это сделать, но по какой-то причине он не будет работать :(Почему этот jQuery «ближайший» код не работает?

Я добавил alert для целей тестирования, но он просто выводит undefined

$(document).ready(function() { 
 
// generate payment reference 
 

 
$("#generate_payment_reference").click(function() { 
 
    $(".amount_received").each(function(index) { 
 
\t \t var thisAmount = parseFloat($(this).val()); 
 
\t \t var paymentRef = ''; 
 
     if (thisAmount > 0) { 
 
      paymentRef += $(this).closest(".invoice_reference").val(); 
 
\t \t \t alert($(this).closest(".invoice_reference").val()); 
 
     } 
 
\t \t $('#payment_reference').val(paymentRef); 
 
    }); 
 
}); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<fieldset> 
 
    <legend>Client Details</legend> 
 

 
    <table class="nobord"> 
 
    <tr> 
 
     <td>Type:</td> 
 
     <td>Landlord </td> 
 
    </tr> 
 
    <tr> 
 
     <td>Name:</td> 
 
     <td>Mr XXX</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Client Bank Account Balance:</td> 
 
     <td>&pound;387.68</td> 
 
    </tr> 
 
    </table> 
 

 
</fieldset> 
 
<fieldset> 
 
    <legend>Outstanding Invoice Details</legend> 
 
    <table class="solid" style="margin:5px;"> 
 
    <tr> 
 
     <th>Invoice #</th> 
 
     <th>Date</th> 
 
     <th>Due Date</th> 
 
     <th>Invoice Total</th> 
 
     <th>Amount Paid</th> 
 
     <th>Amount Due</th> 
 
     <th>Amount Received (&pound;)</th> 
 
    </tr> 
 
    <tr> 
 
     <td><a href="view_invoice.php?invoice_id=496" target="_blank">496</a> 
 
     <input type="text" class="invoice_reference" value="496"> 
 
     </td> 
 
     <td>14/01/16</td> 
 
     <td>14/01/16</td> 
 
     <td>&pound;25.20</td> 
 
     <td>&pound;0.00</td> 
 
     <td>&pound;25.20 
 
     <input type="hidden" name="amount_outstanding[]" value="25.20"> 
 
     </td> 
 
     <td> 
 
     <input type="number" name="amount_received[]" class="amount_received" value="0.00" max="25.20" required>&nbsp; 
 
     <button class="pay_in_full" type="button">Pay in Full</button> 
 
     <input type="hidden" name="invoice_id[]" value="496"> 
 
     <input type="hidden" name="invoice_tenancy_id[]" value="40"> 
 
     <input type="hidden" name="invoice_property_id[]" value="119"> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td><a href="view_invoice.php?invoice_id=497" target="_blank">497</a> 
 
     <input type="text" class="invoice_reference" value="497"> 
 
     </td> 
 
     <td>14/01/16</td> 
 
     <td>14/01/16</td> 
 
     <td>&pound;25.20</td> 
 
     <td>&pound;0.00</td> 
 
     <td>&pound;25.20 
 
     <input type="hidden" name="amount_outstanding[]" value="25.20"> 
 
     </td> 
 
     <td> 
 
     <input type="number" name="amount_received[]" class="amount_received" value="0.00" max="25.20" required>&nbsp; 
 
     <button class="pay_in_full" type="button">Pay in Full</button> 
 
     <input type="hidden" name="invoice_id[]" value="497"> 
 
     <input type="hidden" name="invoice_tenancy_id[]" value="40"> 
 
     <input type="hidden" name="invoice_property_id[]" value="119"> 
 
     </td> 
 
     </td> 
 
    </tr> 
 
    </table> 
 
</fieldset> 
 
<fieldset> 
 
    <legend>Payment Details</legend> 
 

 
    <table class="nobord"> 
 
    <tr> 
 
     <td> 
 
     <label for="invoice_payment_date">Date:</label> 
 
     </td> 
 
     <td> 
 
     <input type="date" id="invoice_payment_date" name="invoice_payment_date" class="datepicker2months" ondblclick="this.value='2016-01-14';" readonly required> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     <label for="total_amount_received">Total Amount Received (&pound;):</label> 
 
     </td> 
 
     <td> 
 
     <input type="number" id="total_amount_received" name="total_amount_received" readonly required> 
 
     <input type="hidden" id="client_bank_account_balance" name="client_bank_account_balance" value="387.68" required> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     <label for="payment_reference">Payment Reference:</label> 
 
     </td> 
 
     <td> 
 
     <input type="text" id="payment_reference" readonly>&nbsp; 
 
     <button id="generate_payment_reference" type="button">Generate</button> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     <label for="invoice_payment_use_balance">Pay from Client Bank Account Balance:</label> 
 
     </td> 
 
     <td> 
 
     <select id="invoice_payment_use_balance" name="invoice_payment_use_balance" required> 
 
      <option value="">Please Select</option> 
 
      <option value="0">No</option> 
 
      <option value="1" selected>Yes</option> 
 
     </select> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     <label for="invoice_payment_method">Method:</label> 
 
     </td> 
 
     <td> 
 
     <select id="invoice_payment_method" name="invoice_payment_method" required> 
 
      <option value="">Please Select</option> 
 
      <option value="2" selected>Bank Transfer</option> 
 
      <option value="1">Cash</option> 
 
      <option value="3">Cheque</option> 
 
      <option value="4">Credit Card</option> 
 
      <option value="5">Debit Card</option> 
 
     </select> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     <label for="invoice_payment_notes">Notes:</label> 
 
     </td> 
 
     <td> 
 
     <textarea id="invoice_payment_notes" name="invoice_payment_notes" rows="6" cols="40"></textarea> 
 
     </td> 
 
    </tr> 
 
    </table> 
 

 
</fieldset>

+1

[ '.closest()'] (https://api.jquery.com/closest/) ищет ближайший предок * * элемент. '.invoice_reference' не является предком. Вам нужно будет сделать еще один [обход дерева] (https://api.jquery.com/category/traversing/tree-traversal/). – Blazemonger

+1

Если вы убираете HTML-код (который я только что сделал в JSFiddle с кнопкой 'Tidy'), иерархия становится немного понятнее. –

ответ

4

Это потому, что ваш .invoice_reference элемент не является предок вашего .amount_received элемента. Вместо этого вы можете перейти к tr элемента и использовать find() тянуть .invoice_reference в том, что:

$(this).closest('tr').find(".invoice_reference").val() 
+0

@TrueBlueAussie. Вы знаете, мой самый ответный ответ здесь на Stack Overflow был представлен почти через 4 года после того, как был задан вопрос, на который он ответил; 1 с половиной года после ответа, который был предоставлен в течение более чем 300 upvotes. Но с течением времени мой ответ с тех пор значительно обогнал остальных довольно ошеломляющими 700 голосами. Этот ответ я разместил через 18 секунд после твоего, но только после того, как ты оставил свой комментарий здесь, я даже знал, что ваш ответ существует. Время - довольно плохая судьба ответа на вопрос. Возможно, люди предпочитают мои, как говорится. –

+0

На самом деле у вас есть удивительное среднее число оборотов для вопросов этой категории. Может быть, мне нужно лучшее фото :) –

+0

Мой собственный вопрос был переполнен жалобами на мой совет по надежности, поэтому я удалил его. Здесь есть еще один +1. Точки на этом сайте бессмысленны (каламбур) :) –

2

Если $(".amount_received").length равно $(".invoice_reference").length, попробуйте использовать .eq() с параметром index; перемещение $('#payment_reference').val(paymentRef); за пределами .each(), чтобы превзойти значение из-за перезаписи. Примечание, дублирование закрытия </td> s по адресу html.

Следует также отметить, что ожидаемый результат не является конкатенированной строкой или добавлением значений в paymentRef переменной?

$(document).ready(function() { 
 
// generate payment reference 
 

 
$("#generate_payment_reference").click(function() { 
 
    var paymentRef = ""; 
 
    $(".amount_received").each(function(index) { 
 
\t \t var thisAmount = parseFloat($(this).val()); 
 
\t \t //var paymentRef = ''; 
 
     if (thisAmount > 0) { 
 
      paymentRef += $(".invoice_reference").eq(index).val(); 
 
     } 
 
\t \t 
 
    }); 
 
    $('#payment_reference').val(paymentRef); 
 
}); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"> 
 
</script> 
 
<fieldset> 
 
<legend>Client Details</legend> 
 

 
<table class="nobord"><tr> 
 
    <td>Type:</td> 
 
\t <td>Landlord </td> 
 
    </tr><tr> 
 
    <td>Name:</td> 
 
\t <td>Mr XXX</td> 
 
    </tr><tr> 
 
    <td>Client Bank Account Balance:</td> 
 
\t <td>&pound;387.68</td> 
 
    </tr></table> 
 

 
</fieldset><fieldset> 
 
<legend>Outstanding Invoice Details</legend><table class="solid" style="margin:5px;"><tr> 
 
    <th>Invoice #</th> 
 
    <th>Date</th> 
 
\t <th>Due Date</th> 
 
    <th>Invoice Total</th> 
 
    <th>Amount Paid</th> 
 
\t <th>Amount Due</th> 
 
\t <th>Amount Received (&pound;)</th> 
 
    </tr><tr> 
 
    <td><a href="view_invoice.php?invoice_id=496" target="_blank">496</a> 
 
\t <input type="text" class="invoice_reference" value="496"> 
 
\t </td> 
 
    <td>14/01/16</td> 
 
\t <td>14/01/16</td> 
 
    <td>&pound;25.20</td> 
 
    <td>&pound;0.00</td> 
 
\t <td>&pound;25.20 
 
\t <input type="hidden" name="amount_outstanding[]" value="25.20"> 
 
\t </td> 
 
\t <td> 
 
\t <input type="number" name="amount_received[]" class="amount_received" value="0.00" max="25.20" required>&nbsp;<button class="pay_in_full" type="button">Pay in Full</button> 
 
\t <input type="hidden" name="invoice_id[]" value="496"> 
 
\t <input type="hidden" name="invoice_tenancy_id[]" value="40"> 
 
\t <input type="hidden" name="invoice_property_id[]" value="119"></td> 
 

 
    </tr> 
 
<tr> 
 
    <td><a href="view_invoice.php?invoice_id=497" target="_blank">497</a> 
 
\t <input type="text" class="invoice_reference" value="497"> 
 
\t </td> 
 
    <td>14/01/16</td> 
 
\t <td>14/01/16</td> 
 
    <td>&pound;25.20</td> 
 
    <td>&pound;0.00</td> 
 
\t <td>&pound;25.20 
 
\t <input type="hidden" name="amount_outstanding[]" value="25.20"> 
 
\t </td> 
 
\t <td> 
 
\t <input type="number" name="amount_received[]" class="amount_received" value="0.00" max="25.20" required>&nbsp;<button class="pay_in_full" type="button">Pay in Full</button> 
 
\t <input type="hidden" name="invoice_id[]" value="497"> 
 
\t <input type="hidden" name="invoice_tenancy_id[]" value="40"> 
 
\t <input type="hidden" name="invoice_property_id[]" value="119"></td> 
 

 
    </tr></table></fieldset> 
 
<fieldset> 
 
<legend>Payment Details</legend> 
 

 
<table class="nobord"><tr> 
 
    <td><label for="invoice_payment_date">Date:</label></td> 
 
\t <td> 
 
\t <input type="date" id="invoice_payment_date" name="invoice_payment_date" class="datepicker2months" ondblclick="this.value='2016-01-14';" readonly required> 
 
\t </td> 
 
    </tr><tr> 
 
    <td><label for="total_amount_received">Total Amount Received (&pound;):</label></td> 
 
\t <td> 
 
\t <input type="number" id="total_amount_received" name="total_amount_received" readonly required> 
 
\t <input type="hidden" id="client_bank_account_balance" name="client_bank_account_balance" value="387.68" required> 
 
\t </td> 
 
    </tr><tr> 
 
    <td><label for="payment_reference">Payment Reference:</label></td> 
 
\t <td> 
 
\t <input type="text" id="payment_reference" readonly>&nbsp;<button id="generate_payment_reference" type="button">Generate</button> 
 
\t </td> 
 
    </tr><tr> 
 
    <td><label for="invoice_payment_use_balance">Pay from Client Bank Account Balance:</label></td> 
 
\t <td><select id="invoice_payment_use_balance" name="invoice_payment_use_balance" required><option value="">Please Select</option><option value="0">No</option><option value="1" selected>Yes</option></select></td></tr><tr> 
 
    <td><label for="invoice_payment_method">Method:</label></td> 
 
\t <td><select id="invoice_payment_method" name="invoice_payment_method" required><option value="">Please Select</option><option value="2" selected>Bank Transfer</option><option value="1">Cash</option><option value="3">Cheque</option><option value="4">Credit Card</option><option value="5">Debit Card</option></select></td></tr><tr> 
 
    <td><label for="invoice_payment_notes">Notes:</label></td> 
 
\t <td><textarea id="invoice_payment_notes" name="invoice_payment_notes" rows="6" cols="40"></textarea></td></tr></table> 
 

 
</fieldset>

+0

Это опасная техника, так как она не охватывает поиск '$ (". Invoice_reference ")' search. Если у вас больше элементов 'class =" invoice_reference "' вне этого 'fieldset, это пойдет не так. –

+0

@TrueBlueAussie Просмотреть обновленный пост, добавлено примечание; '$ (". amount_received "). length' выглядят равными' $ (". invoice_reference"). length' at 'js' – guest271314

+0

Это будет сделано в этом конкретном примере, но что, если у них есть несколько таблиц на странице? Это перерасчет их всех. Просто мое мнение, но поиск в области области более безопасен для обслуживания. –