как получить введенные пользователем данные и идентификаторы в динамически добавляемых строках таблицы? - PullRequest
0 голосов
/ 04 октября 2019

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

$('body').on('change', '[data-action="sumDebit"]', function() { //Attach an event to body that binds to all tags that has the [data-action="sumDebit"] attribute. This will make sure all over dynamically added rows will have the trigger without us having to readd after ever new row.
  var total = 0;
  $('[data-action="sumDebit"]').each(function(_i, e) { //Get all tags with [data-action="sumDebit"]
    var val = parseFloat(e.value); //Get int value from string
    if (!isNaN(val)) //Make sure input was parsable. If not, result come back as NaN
      total += val;
  });
  $('#totaldbt').val(total); //Update value to total
});

var ctr = 1;
var FieldCount = 1;
$('#fst_row').on('click', '.button-add', function() {
  ctr++;
  var cashacc_code = 'cashacc_code' + ctr;
  var cash_narrat = 'cash_narrat' + ctr;
  var cashdeb = 'cashdeb' + ctr;
  var cashcredit = 'cashcredit' + ctr;
  var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + cashacc_code + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><select class="form-control" id=' + cashacc + ' ' + FieldCount + '></select></td><td><input type="text" class=' + "joe" + ' id=' + cash_narrat + ' ' + FieldCount + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe" + ' id=' + cashdeb + ' ' + FieldCount + ' placeholder="NNNN" data-action="sumDebit" /></td><td><input type="number" class=' + "joe" + ' id=' + cashcredit + ' ' + FieldCount + '/></td><td style="width: 4%"><img src="./img/delete.svg" class="dlt-icon" ' + FieldCount + '></td></tr>';
  $('#cashTable').append(newTr);

  $(document).on('click', '.dlt-icon', function() {
    $(this).parents('tr.jsrow').first().remove();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="cashTable" class="table table-bordered table-striped" required>
  <thead>
    <tr>
      <th>A/c Code</th>
      <th>Account Name*</th>
      <th>Narration*</th>
      <th>Debit*</th>
      <th>Credit</th>
    </tr>
  </thead>
  <tbody>
    <tr id="fst_row" class="jsrow">
      <!-- First row -->
      <td>
        <input type="number" id="cashacc_code" placeholder="NNNN" class="form-control" name="cashacc_code" />
      </td>
      <td>
        <select class="form-control selectsch_items" name="cashacc" id="cashacc">
          <option value="Choose and items">Choose and items</option>
          <option value="1">TDS A/c Name 1</option>
          <option value="2">TDS A/c Name 2</option>
        </select>
      </td>
      <td>
        <input type="text" id="cash_narrat" placeholder="Enter here" class="form-control narate" pattern="[a-zA-Z0-9-_.]{1,20}" name="cash_narrat" data-toggle="modal" data-target="#narratModal" />
      </td>
      <td>
        <input type="number" id="cashdeb" placeholder="Debit Amount" data-action="sumDebit" value="100" class="form-control" name="cashdeb" readonly/>
      </td>
      <td>
        <input type="text" id="cashcredit" class="form-control" name="cashcredit" readonly/>
      </td>
      <td class="tblBtn" style="width: 4%">
        <a href="#"><img src="./img/plus.svg" class="insrt-icon button-add"></a>
        <a href="#"><img src="./img/delete.svg" class="dlt-icon dlt-icon"></a>
      </td>
    </tr>
  </tbody>
</table>

FIDDLE Здесь ..

Ответы [ 2 ]

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

Пользовательский ввод можно получить, обратившись к столбцу и строке внутри таблицы

     var table = document.getElementById("cashTable"), sumVal = 0;
            for(var i = 1; i < table.rows.length; i++)
            {
                sumVal = sumVal + parseFloat(table.rows[i].cells[5].innerHTML); 
//here cells is referred to the cell number you want the value if you want the value of all cells of a row then loop through the cells of a row
            }
           alert(sumVal);
            console.log(sumVal);
0 голосов
/ 04 октября 2019

Что вы подразумеваете под идентификаторами ?? на какое действие вы хотели бы получить пользовательские данные и идентификаторы динамически создаваемых строк.

Все есть. У вас есть класс jsrow enter code here для каждого созданного tr. Извлеките все tr и затем извлекайте каждое входное значение, так как у вас есть отдельный класс для каждого ввода.

var rows = $('#cashTable').find('tr.jsrow'); // get all rows.

Затем итерируйте строки в соответствии с вашими потребностями. я пишу прямо, скажем, хочу получить все идентификаторы строки 2. Найти все входы в этой строке, как показано ниже, а затем получить атрибут id .

var inputs = $(rows[0]).find('input'); // all inputs. same way all select as well
// iterate all inputs and grab ID attribute
for(let i =0 ; i< inputs.length; i++ ) {
  var attr = inputs[i].getAttribute('id'); 
  console.log(attr); // id attribute
  console.log(inputs[i].value); // value
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...