Получить значение из текстового поля внутри таблицы и сохранить его как переменную, используя JQuery - PullRequest
2 голосов
/ 23 октября 2019

У меня есть некоторые проблемы с хранением переменной из текстового поля внутри динамически генерируемой таблицы.

Моя цель - я хочу получить значение из текстового поля внутри динамически генерируемой таблицы, а затем сохранить его в базе данных.

Моя проблема в том, что я могу ввести значение в текстовое поле, используя

 $(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 ]

1 голос
/ 23 октября 2019

Переменные находятся в пределах контекста их исполнения, поэтому, когда вы создаете и присваиваете значение своим переменным, у вас фактически есть (как минимум) два контекста:

// 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);

Надеюсь, это поможет!

0 голосов
/ 23 октября 2019

Замените ваш код:

$(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);
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...