Reputation: 339
I have a textbox qty and textbox unit_price in a row. Now I want to pass the value of qty to unit_price. I was able to get the value of qty but I cant pass the value to its to unit_price row, instead it passes the qty value to each unit_price's rows.
HTML:
<table class="data">
<tr>
<td><input="text" class="qty" name="qty[]"></td><td><input="text" class="unit_price" name="unit_price[]"></td>
</tr>
<tr>
<td><input="text" class="qty" name="qty[]"></td><td><input="text" class="unit_price" name="unit_price[]">
</td>
</tr>
<tr>
<td><input="text" class="qty" name="qty[]"></td><td><input="text" class="unit_price" name="unit_price[]">
</td>
</tr>
Here's my jquery:
$('table.data').on('change','.qty',function(){
var val = $(this).parent().parent().find('input[type=text]').val();
alert(val);
$(".unit_price").parent().parent().find('input[type="text"]').val(val);
})
Need some help on how to pass the value of qty to unit_price.
Upvotes: 0
Views: 181
Reputation: 530
Or use .next() method to get the following
$('table.data').on('change','.qty',function(){
$(this).parent().next().find(".unit_price").val($(this).val());
})
Upvotes: 0
Reputation: 74738
You need to use .closest()
to get to the closest parent instead of .parent()
twice and make sure to be in the context of the selector with this
:
$('table.data').on('change','.qty',function(){
var val = $(this).val();
alert(val);
$(this).closest('tr').find(".unit_price").val(val);
})
Upvotes: 2
Reputation: 2425
Here you go:
$('table.data').on('change','.qty',function() {
var qtyInput = $(e.target)
qtyInput.parents("tr").find('.unit_price').val( qtyInput.value );
})
Upvotes: 0
Reputation: 2978
Assuming that retrieving your unit price is correct. Find the previous textbox using jquery prev() function.
var unitPriceObj = $(this).parent().parent().find('input[type=text]');
var unitPrice = unitPriceObj .val(); // get unit price value
unitPriceObj.prev('input').val(unitPrice ); // assign it to qty
Upvotes: 0