I have some problems with storing a variable from a textbox inside a dynamically generated table.
My goal is, I want to get the value from the textbox inside a dynamically generated table, then store it to the database.
My problem is, I can the textbox value using
$(this).closest('tr').find("input").each(function() {
var stock = $(this).val();
})
But when I call it outside the function, the stock value doesn't store in the variable.
Here is the code to retrieve the data
$(document).on("click", ".tambahSparepart", function(event){
$(this).closest('tr').find("input").each(function() {
var stock = $(this).val();
})
alert('stock');
})
Here is the HTML code where the textbox is generate
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Stock Code</th>
<th style="padding-right: 265px">Stock Description</th>
<th>UM</th>
<th>Stock Available</th>
<th>Need</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
foreach ($data->result() as $row) {;?>
<tr>
<td><?php echo $row->stock_code;?></td>
<td><?php echo $row->stock_description;?></td>
<td><?php echo $row->um;?></td>
<td><?php echo $row->stock;?></td>
<td>
<input type="text" name="stock" class="form-control" placeholder="Stock...">
</td>
<td>
<button class="tambahSparepart btn btn-block btn-default"
stock_code="<?php echo $row->stock_code;?>"
>
Tambah
</button>
</td>
</tr>
<?php }
;?>
</tbody>
<tfoot>
<tr>
<th>Stock Code</th>
<th>Stock Description</th>
<th>UM</th>
<th>Stock Available</th>
<th>Need</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
Thank you
var stock = ''; $(this).closest('tr').find("input").each(function() { stock = $(this).val(); })initialize it outside .each