2016-04-26 67 views
0

我有一個表格,前兩個單元格是inputfields,我試圖映射數組內的所有表格數據。但我不知道如何從輸入字段獲取數據,知道它只映射其他數據。帶輸入字段的jQuery map()表

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

}); 
+1

'$回報(本)。是( ':有(:輸入)')$(?:輸入「,這).val():$(this).text();' –

+0

太好了!謝謝 – Bart

+0

很高興幫助你:) –

回答

0

td像下面的檢查input

$('.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])); 
}); 
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(); 
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])); 
});