【问题标题】:How to take table data into an array in jQuery?如何将表格数据放入jQuery中的数组中?
【发布时间】:2019-01-05 09:13:21
【问题描述】:

我想从动态表中获取值并在 ajax 调用中发送值,我动态增加表行但是当我尝试将行值放入数组时它只存储第一行值。

我的 HTML 代码:

<table class="table table-bordered table-hover table-sm" id="SizeTable">
<thead>
    <tr>
        <th><input type="checkbox" class="allGridCheck"></th>
        <th style="width: 50%;">Size</th>
        <th style="width: 50%;">Quantity</th>
        <th class="hidden"></th>
    </tr>
</thead>
<tbody class="GridContent table-secondary" id="GridBody">
    <tr class="GridFields">
        <td><input type="checkbox" class="singleGridCheck"></td>
        <td>
            <select class="form-control form-control-sm size-id" name="SizeId"></select>
        </td>
        <td>
            <input type="number" class="form-control form-control-sm quantity-value" name="QuantityValue" />
        </td>
        <td class="hidden"></td>
    </tr>
</tbody>

这是我的脚本:

var sizesId = [];
var sizesValue = [];

$('#SizeTable > tbody  > tr').each(function() {
  var sizeId = $('.size-id option:selected').val();
  var sizeValue = $('.quantity-value').val();

  if (sizeId) {
    sizesId.push(sizeId);
  }

  if (sizeValue) {
    sizesValue.push(sizeValue);
  }

  alert(sizeId);
});

alert(sizesId);
alert(sizesValue);

如何将值放入数组???

【问题讨论】:

    标签: javascript jquery html ajax


    【解决方案1】:

    因为你总是拿选择的项目

    $('.size-id option:selected').val(); 
    

    在数组中获取一项是正常的

    使用这个

    $('#SizeTable > tbody  > tr').each(function() {
    
    
               var sizeId = $(this).find('.size-id').val();
               var sizeValue = $(this).find('.quantity-value').val();
    
               if (sizeId) {
                   sizesId.push(sizeId);
               }
    
               if (sizeValue) {
                   sizesValue.push(sizeValue);
               }
    
               alert(sizeId);
           });
    

    【讨论】:

      【解决方案2】:

      查看以下修改后的代码以获取动态表的值。

      var sizesId = [];
      var sizesValue = [];
      $('#SizeTable > tbody  > tr > td').each(function(ind, val) {
           var varSizeId = $(val).find(".size-id option:selected").text();
           var varSizeValue = $(val).find("input[name='QuantityValue']").val();
           if (varSizeId) {
               sizesId.push(varSizeId);
           }
           if (varSizeValue) {
               sizesValue.push(varSizeValue);
           }
       });
       console.log(sizesId);
       console.log(sizesValue);
      

      【讨论】:

        【解决方案3】:

        jQuery 让我们变得懒惰,看不到明显

        我想到了遍历每个单元格的复杂性和冗余性,然后我恍然大悟,您的&lt;table&gt; 的值不是来自&lt;table&gt;,而是来自&lt;select&gt;&lt;input&gt;。 jQuery 对象在很多方面就像一个数组,所以只需忽略表格,只使用对象本身。顺便说一句,从选择中获取值比您在代码中尝试的要简单得多。只需从 select 中获取值:

        var value = $('select').val(); // jQuery
        var value = document.querySelector('select');  // JavaScript
        

        真正的快速解释。您需要迭代(又名循环➰)正确的 jQuery 对象。如果您正在查找一组&lt;select&gt;s 的值,请不要遍历&lt;table&gt;...遍历&lt;select&gt;s 组


        演示

        $('#rowBtn').on('click', addRows);
        $('#delData').on('click', deleteData);
        $('#fillTab').on('click', fillTable);
        $('#xtcData').on('click', extractData);
        $('.chkAll').on('change', checkAll);
        
        
        
        function addRows(e) {
          var dock = $('#gridCore');
          var row = $('.gridRow');
          var qty = Number($('#rowUI').val());
          var rQty = $('#gridTable')[0].rows.length;
        
          for (let i = 0; i < qty; i++) {
            var dupe = row.clone(true, true).appendTo(dock);
            dupe.find(':checkbox').addClass('chk');
          }
          return console.log(`
          Rows.: ${parseInt(rQty, 10)}
          Cells: ${parseInt(rQty, 10) * 2}`);
        }
        
        function fillTable(e) {
          $('.size, .qty').each(function() {
            var sVal = ["S", "M", "L"];
            var sRng = getRandom(0, 2);
            var qRng = getRandom(0, 600);
            if ($(this).is('.size')) {
              $(this).val(sVal[sRng]);
            } else {
              $(this).val(qRng);
            }
          });
        }
        
        function extractData(e) {
          var sz = [];
          var qy = [];
          var sZqY = {};
          $('.size, .qty').each(function(idx) {
            if ($(this).is('.size')) {
              var SV = $(this).val();
              sz.push(SV);
            } else {
              var QV = $(this).val();
              qy.push(QV);
            }
          });
          sZqY.qty = qy;
          sZqY.size = sz;
          return console.log(JSON.stringify(sZqY));
        }
        
        function deleteData(e) {
          var rows = $('#gridTable')[0].rows.length;
          var chx = $('.chk');
          chx.each(function(idx) {
            var row = $(this).closest('.gridRow');
            if ($(this)[0].checked) {
              row.remove();
              rows--;
              if (rows === 1) {
                return false;
              }
            }
          });
          return console.log(rows);
        }
        
        function checkAll(e) {
          if ($(this)[0].checked) {
            $('.chk').prop('checked', true);
          } else {
            $('.chk').prop('checked', false);
          }
          return $('.chk').prop('checked');
        }
        
        function getRandom(min, max) {
          min = Math.ceil(min);
          max = Math.floor(max);
          return Math.floor(Math.random() * (max - min + 1)) + min;
        }
        label {
          display: block
        }
        
        #xtcData,
        #fill {
          transform: translateX(0px);
          transition: 0s
        }
        
        .as-console-row.as-console-row::after {
          content: '';
          padding: 0;
          margin: 0;
          border: 0;
          width: 0;
        }
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
        
        <form id='ui'>
        
          <button class="btn btn-primary float-right" type="button" data-toggle="collapse" data-target="#colA">
            Table Tools
          </button>
        
          <header class="collapse" id="colA">
            <aside class="card card-body" style='padding:0;line-height:1;'>
              <label class="input-group mb-3" for='rowUI'>
          <input id='rowUI' type="number" class="form-control" placeholder="Enter Number of Rows" min='1' max='100' style='text-align:center;'>
          <label class="input-group-append" for='rowBtn'>
            <button id="rowBtn" class="btn btn-warning" type="button" >Generate Rows</button>
          </label>
              </label>
        
            </aside>
            <button id='delData' class="btn btn-danger float-right" type='button'>
            Delete Data
          </button>
            <button id='xtcData' class="btn btn-info float-right" type='button'>
            Extract Data
          </button>
            <button id='fillTab' class="btn btn-success float-right" type='button'>
            Fill Table
          </button>
          </header>
        
          <table id="gridTable" class="table table-bordered table-hover table-sm">
            <thead>
              <tr>
                <th style="width:5%;"><input class="chkAll" type="checkbox"></th>
                <th style="min-width: 60%;">Size</th>
                <th style="width: 30%;">Quantity</th>
                <th class="hidden"></th>
              </tr>
            </thead>
            <tbody id="gridCore" class="table-secondary">
              <tr class="gridRow">
                <td><input type="checkbox"></td>
                <td>
                  <select class="form-control form-control-sm size" name="size">
                    <option value=''>Pick a Size</option>
                    <option value='S'>Small</option>
                    <option value='M'>Medium</option>
                    <option value='L'>Large</option>
                  </select>
                </td>
                <td>
                  <input type="number" class="form-control form-control-sm qty" name="qty" min='1' max='600' style='text-align:center'>
                </td>
                <td class="hidden"></td>
              </tr>
            </tbody>
          </table>
        
        </form>
        
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-06-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-29
          • 1970-01-01
          相关资源
          最近更新 更多