2013-12-09 130 views
0

我對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); 
    }) 
}); 

感謝。

+1

什麼額外的''標籤在'addRow'單擊處理? – srquinn

+0

你已經標記了這個「php」但沒有使用,你想在PHP或jQuery的解決方案嗎?這可以在兩者中完成。 – Jeppe

+0

http://jsfiddle.net/gcL9H/7/ – cmorrissey

回答

1

在其他的答案說,你添加標記問題與<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/

+0

接受此爲額外的幫助處理結果,再次感謝。 – Spark

0
$('#addRow').click(function() { 
    $('#categoriesTable').append("<tr><td><input type='text'/></td><td><input type='checkbox'/></td></tr>"); 
}); 

簡單地殺死多餘<tr>標籤與包裝<tr>整個模板字符串,你應該是好去。您每次添加時都會添加額外的標籤。

看到這個fiddle

0

有兩個問題:

額外的行被添加的:

$('#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/