2015-08-31 74 views
0

我能夠使用jQuery將預先填充的表格與數據轉換爲JSON對象。下面是代碼:使用jQuery將用戶輸入從html表格轉換爲JSON

var header = $('table thead tr th').map(function() { 
return $(this).text(); 
}); 

var tableObj = $('table tbody tr').map(function (i) { 
    var row = {}; 
    $(this).find('td').each(function (i) { 
     var rowName = header[i]; 
     row[rowName] = $(this).text(); 
    }); 
    return row; 
}).get(); 

JSON.stringify(tableObj); 

和HTML表是這樣的:

<table> 
     <thead> 
     <tr> 
      <th>Name</th> 
      <th>E-mail</th> 
      <th>Job</th> 
     </tr> 
     </thead> 

     <tbody> 
     <tr> 
      <td>jason</td> 
      <td>[email protected]</td> 
      <td>Developer</td> 
     </tr> 
     <tr> 
      <td>ted</td> 
      <td>[email protected]</td> 
      <td>Bear</td> 
     </tr> 
     </tbody> 
</table> 

現在我的任務就是真正處理空白表格的用戶輸入。當用戶加載頁面時,表格是空的,沒有值,用戶在輸入並點擊提交後,我想將用戶輸入數據轉換爲JSON對象並將其傳遞迴後端。

我試圖做到這一點由經線tableform,並添加<input>標籤在每個<td>,這樣的事情:

<form> 
    <table> 
     <tbody> 
      <tr> 
       <td><input type="text"/></td> 
       <td><input type="text"/></td> 
       <td><input type="text"/></td> 
      </tr> 
      <tr> 
       <td><input type="text"/></td> 
       <td><input type="text"/></td> 
       <td><input type="text"/></td> 
      </tr> 
     </tbody> 
    </table> 
    <button type="submit">Submit</button> 
</form> 

我嘗試使用從jQuery的的.submit()方法使它工作,但我得到語法錯誤:

$('form').submit(
var header = $('table thead tr th').map(function() { 
return $(this).text(); 
}); 

var tableObj = $('table tbody tr').map(function (i) { 
    var row = {}; 
    $(this).find('td').each(function (i) { 
     var rowName = header[i]; 
     row[rowName] = $(this).text(); 
    }); 
    return row; 
}).get(); 

JSON.stringify(tableObj); 
); 

我應該如何更改我的代碼,使其工作?

+0

你有沒有考慮過使用類似DataTables(http://www.datatables.net)的東西?使用JSON對象自動構建表並允許更多功能。 – jonmrich

回答

1

發生這種情況,因爲td中沒有文字。你需要找到輸入的值。

1)你必須得到inputtd

2)你需要得到value of the input

也可以嘗試看看editable div

試試這個:

row[rowName] = $(this).find('input').val(); 
+1

另外,他沒有正確定義'submit()'處理程序。這是一個工作小提琴:http://jsfiddle.net/8uhdhge6/ – dave