2013-08-20 33 views
16

我有一個HTML表格,每行都有一個複選框。
我想遍歷表格,看看是否有任何複選框被選中。
以下不工作:在html表格上循環並得到選中的複選框(jQuery)

$("#save").click(function() { 
    $('#mytable tr').each(function (i, row) { 
     var $actualrow = $(row); 
     checkbox = $actualrow.find('input:checked'); 
     console.log($checkbox); 
}); 

打印在控制檯以下:

[prevObject: jQuery.fn.jQuery.init[1], context: tr, selector: "input:checked", constructor: function, init: function…]

每行無論任何複選框是否被選中。

更新
同一個問題有:

$('#mytable tr').each(function (i, row) {                         
    var $actualrow = $(row); 
    $checkbox = $actualrow.find(':checkbox:checked'); 
    console.log($checkbox); 
}); 
+3

是的,一個jQuery對象被打印到控制檯,這是正常的。你有沒有檢查它的'長度'屬性? –

+1

您是否試過'$ actualrow.find('input')。is(':checked');' –

+0

log'$ checkbox.length'。長度是否爲零? –

回答

48

用這個代替:

$('#save').click(function() { 
    $('#mytable').find('input[type="checkbox"]:checked') //... 
}); 

讓我解釋一下,你有什麼選擇呢: input[type="checkbox"]意味着這將匹配每個<input />與類型屬性type等於checkbox 之後::checked將匹配所有選中的複選框。

你也可以遍歷這些複選框有:

$('#save').click(function() { 
    $('#mytable').find('input[type="checkbox"]:checked').each(function() { 
     //this is the current checkbox 
    }); 
}); 

這裏是JSFiddle演示。


而這裏是一個演示,它正確地解決了您的問題http://jsfiddle.net/DuE8K/1/

$('#save').click(function() { 
    $('#mytable').find('tr').each(function() { 
     var row = $(this); 
     if (row.find('input[type="checkbox"]').is(':checked') && 
      row.find('textarea').val().length <= 0) { 
      alert('You must fill the text area!'); 
     } 
    }); 
}); 
+0

我想單獨獲取。如果複選框被選中,但同一行中的文本框未被填充,我想顯示一個提醒 – Jim

+0

好的,讓我給你一個例子。 –

+0

@Jim檢查這個解決方案http://jsfiddle.net/DuE8K/1/ –

-1

在您的代碼中是缺少});

$("#save").click(function() { 
    $('#mytable tr').each(function (i, row) { 
     var $actualrow = $(row); 
     $checkbox = $actualrow.find('input:checked'); 
     console.log($checkbox); 
    }); 
}); 
0
下面的代碼片段啓用取決於是否在頁面上至少一個複選框被選中/禁用按鈕。
$('input[type=checkbox]').change(function() { 
    $('#test > tbody tr').each(function() { 
     if ($('input[type=checkbox]').is(':checked')) { 
      $('#btnexcellSelect').removeAttr('disabled'); 
     } else { 
      $('#btnexcellSelect').attr('disabled', 'disabled'); 
     } 
     if ($(this).is(':checked')){ 
      console.log($(this).attr('id')); 
     }else{ 
      console.log($(this).attr('id')); 
     } 
    }); 
}); 

這是演示JSFiddle

相關問題