带有输入字段的jQuery map()表

时间:2016-04-26 06:57:41

标签: jquery

我有一个表格,其中前两个单元格是输入字段,我试图映射数组中的所有表格数据。但我不知道如何从输入字段获取数据,知道它只映射其他数据。

JSFiddle

    <table width="100%">
  <thead>
    <tr>
      <td><strong>Amount</strong></td>
      <td><strong>Price</strong></td>
      <td><strong>Articleid</strong></td>
      <td><strong>Descr</strong></td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input class="amount" type="text" value="1"></td>
      <td><input class="purchprice" type="text" value="2.00"></td>
      <td>210003</td>
      <td>Example_1</td>
    </tr>
    <tr>
      <td><input class="amount" type="text" value="1"></td>
      <td><input class="purchprice" type="text" value="19.25"></td>
      <td>128025</td>
      <td>Example_2</td>
    </tr>
    <tr>
      <td><input class="amount" type="text" value="3"></td>
      <td><input class="purchprice" type="text" value="23.45"></td>
      <td>124005</td>
      <td>Example_3</td>
    </tr>
    </tbody>
</table>

jQuery

<button type="button" class="map">Map table</button>

$('.map').on('click', function() {

  var tableData = $('table tbody td').map(function() {
    return $(this).text();
  }).get();

  console.log($.trim(tableData[0]));
  console.log($.trim(tableData[1]));
  console.log($.trim(tableData[2]));
  console.log($.trim(tableData[3]));

});

3 个答案:

答案 0 :(得分:1)

检查td包含 map() 中的输入字段,并根据它返回值。

var tableData = $('table tbody td').map(function() {
  return $(this).is(':has(:input)') ? // check td contains input 
    $(':input', this).val() : // if contains return it's value
    $(this).text(); // else return text content
}).get();

答案 1 :(得分:0)

检查input中的td,如下所示。

$('.map').on('click', function () {
    var tableData = $('table tbody td').map(function () {
        var input = $('input', this);
        return input.length > 0 ? input.val() : $(this).text();
    }).get();

    console.log($.trim(tableData[0]));
    console.log($.trim(tableData[1]));
    console.log($.trim(tableData[2]));
    console.log($.trim(tableData[3]));
});

答案 2 :(得分:0)

尝试检查.map

内的标记名称
$('.map').on('click', function() {

  //combine input elements and tds with no inputs
  var tableData = $('table tbody td:not(:has(input)),table tbody td input').map(function() {
    //check the tagName and perform relevant action.
    return this.tagName == "INPUT" ? this.value : this.textContent;
  }).get();

  console.log($.trim(tableData[0]));
  console.log($.trim(tableData[1]));
  console.log($.trim(tableData[2]));
  console.log($.trim(tableData[3]));
});