У меня есть некоторые проблемы с хранением переменной из текстового поля внутри динамически сгенерированной таблицы.
Моя цель - я хочу получить значение из текстового поля внутри динамически генерируемой таблицы, а затем сохранить его в базе данных.
Моя проблема, я могу значение текстового поля, используя
$(this).closest('tr').find("input").each(function() {
var stock = $(this).val();
})
Но когда я вызываю его вне функции, значение stock не сохраняется в переменной.
Вот код для извлечения данных
$(document).on("click", ".tambahSparepart", function(event){
$(this).closest('tr').find("input").each(function() {
var stock = $(this).val();
})
alert('stock');
})
Вот код HTML, где генерируется текстовое поле
<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>
Спасибо
2 ответа
Замените свой код:
$(document).on("click", ".tambahSparepart", function(event){
$(this).closest('tr').find("input").each(function() {
var stock = $(this).val();
})
alert('stock');
})
К этому:
$(document).on("click", ".tambahSparepart", function(event){
var stock = $(this).closest('tr').find("input").val();
alert(stock);
});
Переменные находятся в пределах контекста их исполнения, поэтому при создании и назначении значения для ваших переменных у вас фактически есть (как минимум) два контекста:
// Here is the global scope of execution, assuming all of this does not happen in another function:
var outerVar = 123;
$(this).closest('tr').find("input").each(
function() {
// Here you define another context of execution by declaring a function, that is a piece of code that is not executed right away, thus needs a different context.
// Here you are executing your function multiple times inside a loop, so there will be multiple assignment of some value to different variables all named 'stock'
var stock = $(this).val();
// Inside this function you will have access to the outer and inner context variables
console.log(outerVar, stock) // 123, 'some value'
}
)
// Outside the function you will not have access to the function's inner context variables
console.log(outerVar, stock) // 123, undefined
Итак, если вы хотите, чтобы два контекста взаимодействовали, вы можете создать переменную во внешней области видимости, а затем обновить ее из внутренней области. Вот пример с вашим случаем:
// Here we defined a global variable, and since we are going to have multiple values, we give it an empty array as value.
var stocks = [];
$(this).closest('tr').find("input").each(
function() {
var stock = $(this).val();
// At each iteration we push the current value of stock into the global array
stocks.push(stock);
}
)
console.log(stocks);
Надеюсь это поможет !
Новые вопросы
php
PHP - это широко используемый высокоуровневый, динамический, объектно-ориентированный и интерпретируемый язык сценариев, в первую очередь предназначенный для серверной веб-разработки. Используется для вопросов о языке PHP.