循环遍历多个表单并在jquery中获取其输入值

时间:2017-11-02 20:53:27

标签: javascript jquery

我使用jquery动态生成表单。如何遍历所有表单并提醒其输入值。

生成表格的代码



$.ajax({
  method: 'GET',
  url: 'api/PayrollSystem/GetEmployeeSalaryAmount?AdminId=' + 1,
  success: function(data) {

    if (Object.keys(data).length == 0) {
      $.alert({
        title: 'Saved',
        content: 'Account Number Saved!',
      });
      var row = ('<tr ><td colspan="3" text-align="center"> <b>No Registered Users</b></td></tr>');
      $('.EmpTable').append(row);
    } else {
      $.each(data, function(index, value) {
        var rows = ('<div id="form_div"><form method="post"><table  class="table table-hover employee_table' + index + ' " align=center><thead><tr><td><b>Employee</td> <td><b>Amount</td></tr></thead><tbody><tr><td><b>' + value.FullName + '</b></td><td><input type="hidden" class="form-control Leavename" name="Leavename[]" value="Basic" placeholder="Enter Leave Name">  <input readonly class="form-control LeaveAmount" type="number" name="LeaveAmount[]" value=' + value.SalaryAmount + ' /><input  class="form-control EmpId" type="hidden" name="Id[]" value=' + value.Id + ' /></td></tr><tr id="row' + index + 1 + '"><td><input type="text" class="form-control Leavename" name="Leavename[]" placeholder="Enter Leave Name">  </td><td>   <input type="number" class="form-control LeaveAmount" name="LeaveAmount[]" placeholder="Enter Leave Amount"></td>  </tr></tbody> </table> <input type="button" class="btn btn-success addRow" onclick="add_row(' + index + '); " value=" + Add More Payroll Item"></form>  </div><hr />');

        $('.EmpTable').append(rows);

      });

    }

  }
});
&#13;
&#13;
&#13;

我在哪里尝试按ID输入输入字段的值

&#13;
&#13;
$('#saveAdj').click(function() {
  $('form').each(function() {

    alert($('.EmpId').val());
  });
});
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

$('#saveAdj').click(function() {
  $('form').each(function() {
    var thisForm = this;
    alert($('.EmpId', thisForm).val());
  });
});

$('selector', container)将帮助您仅从容器中搜索;

答案 1 :(得分:0)

您没有提供查找.EmpId的位置的任何上下文。

传递给 each() 方法的回调函数将自动传递用于访问要枚举的集合的值。如果您使用这些参数值,则可以通过将 as the second argument 传递给JQuery对象来提供该上下文。

$('#saveAdj').click(function() {
  // JQuery's .each() method will automatically pass 3 arguments
  // to the provided callback function:
  //  a reference to the index position of that element
  //  a reference to the element being enumerated at the moment
  $('form').each(function(index, element) {

    // The element argument can be passed as the second argument to 
    // the JQuery object (after the selector) to provide context for where to search
    alert($('.EmpId', element).val());
  });
});