2012-04-15 53 views
0

假设我有以下表格:如何处理表格中只检查过的行?

<table> 
    <thead> 
    <tr> 
     <th>Column 1</th> 
     <th>Column 2</th> 
     <th>Column 3</th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr> 
     <td>A1</td> 
     <td><input type="checkbox"/> A2</td> 
     <td>A3</td> 
    </tr> 
    <tr> 
     <td>B1</td> 
     <td><input type="checkbox"/> B2</td> 
     <td>B3</td> 
    </tr> 
    <tr> 
     <td>C1</td> 
     <td><input type="checkbox"/> C2</td> 
     <td>C3</td> 
    </tr> 
    </tbody> 
</table> 

我想只为其复选框被选中的行生成从表JSON。我为“插入检查”填入了什么?

var myRows = []; 
var $headers = $("th"); 
var $rows = $("tbody tr").each(function(index) { 
    $cells = $(this).find("td"); 
    myRows[index] = {}; 
    $cells.each(function(cellIndex) { 
    // Insert Check Here 
    myRows[index][$($headers[cellIndex]).html()] = $(this).html(); 
    });  
}); 

var myObj = {}; 
myObj.myrows = myRows; 
alert(JSON.stringify(myObj));​ 
+0

你只有一个排在它的复选框的数组。也许你正在寻找序列化选中列? – 2012-04-15 16:31:42

+0

我的不好,它的一个专栏。修改后的问题来反映它。 – Rolando 2012-04-15 16:37:35

回答

1

我已经添加了If语句测试,如果TD包含检查或不复选框,看到代码

// Loop through grabbing everything 
    var myRows = []; 
    var $headers = $("th"); 
    var $rows = $("tbody tr").each(function(index) { 
     $cells = $(this).find("td"); 
     myRows[index] = {}; 
     $cells.each(function(cellIndex) { 
     if($(this).find('checkbox').is(':checked')) //Find the checkbox within the TD and test if it's checked or not 
     { 
      myRows[index][$($headers[cellIndex]).html()] = $(this).html(); 
     } 
     });  
    }); 

// Let's put this in the object like you want and convert to JSON (Note: jQuery will also do this for you on the Ajax request) 
var myObj = {}; 
myObj.myrows = myRows; 
alert(JSON.stringify(myObj));​ 
+0

myRows变量显示为空,并在弹出的警告框中添加检查。 – Rolando 2012-04-15 16:36:30

+0

我看到你的评论代码,并推测其余的工作,因此,我只为你添加了'if'语句。请参阅下面的一些其他答案,通常显示解决此任务的更简单的方法。 – 2012-04-15 16:52:48

+0

我发布的代码按原样运行,但会返回表中每行的内容(不检查行是否有复选框)。很奇怪。 – Rolando 2012-04-15 17:06:51

1

与尝试:

var selectedRowsHTML = ""; 

$('table input:checked').each(function() { 
    selectedRowsHTML += $(this).closest('tr').html(); 
}); 

console.log("This is the HTML for selected rows: "+ selectedRowsHTML); 

随着 “:选中” 选择你只能说是你的表内确认输入。遍历它们,找到“最接近('tr')”的父行。就这些而言,你可以获得每一行的HTML(或任何你想要做的事情)。

0

的评论怎么样从而

$("table input:checked") //filter based on your requirement 
.each(function() 
{ 
    var td=$(this).parent(); //gets the `td`, do the necessary 
}); 
0

你可以使用复选框:检查选择器和最接近的查找特定类型的最近元素。

var selectedRows = []; 
$('table input:checkbox:checked').each(function() { 
    selectedRows.push($(this).closest('tr')) 
}); 

selectedRows包含选定表行