[英]Get input values of dynamically created input elements
我是Web開發的新手,我想要實現的是找到的每一行的當前行所有輸入值的數組,例如:test1,true
雖然我可以獲取動態創建的輸入值,但最終還是會遇到一堆空白,可能還有標題嗎? 我也不確定我獲取值的方法是否是最佳解決方案。 這是我到目前為止所擁有的: http : //jsfiddle.net/gcL9H/2/
<table id='categoriesTable' border='1'>
<tr>
<th>Category</th>
<th>X</th>
</tr>
<tr id='data'>
<td><input value='test1' type='text' /></td>
<td><input type='checkbox' /></td>
</tr>
</table>
<button id="addRow">Add</button>
<button id="saveCategories">Results</button>
$('#addRow').click(function()
{
$('#categoriesTable').append("<tr></tr><tr></tr><td><input type='text'/></td><td><input type='checkbox'/></td>");
});
$('#saveCategories').click(function()
{
$("#categoriesTable tr").each(function()
{
var row = [];
$(this).find('td').each(function()
{
var type = $(this).find('input').attr('type');
if(type == "text")
row.push($(this).find('input').val());
else
if(type == "checkbox")
row.push($(this).find('input').is(":checked"));
})
alert(row);
})
});
提前致謝。
如其他答案中所述,您可以使用<tr>
標簽添加標記問題
$('#addRow').click(function(){
$('#categoriesTable').append("<tr><td><input type='text'/></td><td><input type='checkbox'/></td></tr>");
});
收集對象數組中的文本/復選框值:
$('#saveCategories').click(function(){
var rows = [];
// iterates each TR, skip header one
$("#categoriesTable tr").each(function() {
if ( $('td',this).length>0) { // exclude header row
var $td = $('td',this);
// push an object of the row with label / checked properties
rows.push({
label: $td.eq(0).find('input').val(),
checked: $td.eq(1).find('input').is(':checked')
});
}
});
// display results
$("#results").empty();
$(rows).each(function(index,element) {
$("#results").append('row:' + index + ', label:' + element.label + ', checked:' + element.checked + '<br/>');
});
});
我添加了<div id="results"></div>
來顯示收集的值。
小提琴: http : //jsfiddle.net/gcL9H/13/
$('#addRow').click(function() {
$('#categoriesTable').append("<tr><td><input type='text'/></td><td><input type='checkbox'/></td></tr>");
});
只需殺死多余的<tr>
標記並用<tr>
包裹整個模板字符串,就可以了。 每次添加時,您都會添加額外的標簽。
看到這個小提琴
有兩個問題:
正在添加額外的行:
$('#categoriesTable').append("<tr><td><input type='text'/></td><td><input type='checkbox'/></td></tr>");
// Remove all the extra <tr></tr>'s and just have one <tr> at the start,
// one </tr> at the end
在第一行添加一個類,以便您可以忽略該類
<tr class="header">
<th>Category</th>
<th>X</th>
</tr>
並進行以下選擇:
$("#categoriesTable tr:not(.header)").each(function()
更新的小提琴: http : //jsfiddle.net/gcL9H/3/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.