I have a form in which i have 2 text fields debit_amount and credit_amount. Now i want a script to clear debit_amount field if i enter any value in credit_amount and vice versa. Both the text fields in same row. Here is my code snippet:
<td class="ta-right">
<%= text_field_tag "tablel[line_items_attributes][#{index}][amount]", line_item.amount, :size =>4, :id => "amount", :maxlength => 18, :onkeydown => "return numbersOnly(event);", :class=>"bg-focus form-control text-right"%>
</td>
<td class="ta-right">
<%= text_field_tag "tablel[line_items_attributes][#{index}][credit_amount]", line_item.amount, :size =>4, :id => "amount", :maxlength => 18, :onkeydown => "return numbersOnly(event);", :class=>"bg-focus form-control text-right"%></td>
and in script file i have written:
var i = 0;
$('table#line_items tbody tr').each(function(){
if (($('table#line_items tbody tr:eq(' + i + ')').is(":visible")) && $('table#line_items tbody tr:eq(' + i + ') #amount').val() && $('table#line_items tbody tr:eq(' + i + ') #credit_amount').val()) {
$('#amount').focusout(function(){
alert('debit');
$('table#line_items tbody tr:eq(' + i + ') #amount').val(' ');
});
$('#credit_amount').focusout(function(){
alert('credit');
$('table#line_items tbody tr:eq(' + i + ') #credit_amount').val(' ');
});
}
i++;
});
Any help would be appreciated
i
is changed long before the focus events occur! You can't add event handlers in a loop and expect them to correctly reference a global variable.#amount
) which is invalid HTML. Use another class instead of an id.