Look at the HTML table below:
$(document).on('change', '[name="item_inline"]', function(e) {
var $this = $(this);
var $inp = $this.closest('tr').find('[name="rtn_qty[item_id]"]');
var qty = $this.closest('tr').find('.qty').text();
$inp.val(qty);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<td><input type="checkbox" name="select_all" id="select_all" value="1"></td>
<td>Item Name</td>
<td>Qty</td>
<td>Return Qty</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="item_inline" value="1"></td>
<td>Name 01</td>
<td class="qty">150</td>
<td><input type="text" name="rtn_qty[item_id]" value="">
</tr>
<tr>
<td><input type="checkbox" name="item_inline" value="1"></td>
<td>Name 02</td>
<td class="qty">250</td>
<td><input type="text" name="rtn_qty[item_id]" value="">
</tr>
<tr>
<td><input type="checkbox" name="item_inline" value="1"></td>
<td>Name 03</td>
<td class="qty">350</td>
<td><input type="text" name="rtn_qty[item_id]" value="">
</tr>
</tbody>
</table>
Using this table, let say if I checked select_all
check box, then I need to fill all the input under Return Qty column with the values of qty column. According to the above table input values should be (150,250,350). And other thing is, if I click on a checkbox inside tr
then input
of that row should be fill out the qty value of that same row.
I tried the similar way to select_all
checkbox with each
loop, But I confuse how I use each
for this.
Hope somebody may help me out.
2
Answers
One solution (using each on tr) is to reuse what you have:
Step 1: convert your handler to a function so that it can be reused. Pass in
tr
as a parameter:Step 2: change your handler to use function (and test it)
Step 3: on the "all" change, get all the rows then pass each one to your function:
Put together:
With some small changes, we can make it more user friendly
As noted in the comments, .val() has a an overload which allows you to make a single call to .val, eg:
there may be a better way to use .val() here, but it shows the concept.
I think the easiest solution is catch change event of any table > tbody > input[type="checkbox"]
And catch change event of input[name="select_all"] and do click in the earlier inputs.
I hope it helps 🙂