迭代复选框javascript?

时间:2014-01-08 15:38:40

标签: javascript php jquery html

我有一个选择/检查所有复选框id = hap

的功能
$(function () {
       $('#select-all').click(function (event) {

           var selected = this.checked;

           $('#hap').each(function () {    this.checked = selected; });

       });
    }); 

这是我选中所有

的复选框
<input type='checkbox' id='select-all'><label for='select-all'>Delete all</label>

我将它用于我用php提取的选择数据

$data=mysql_query("SELECT*FROM comment where news_id='$id'");
    $x=0;
    while($a=mysql_fetch_array($data)){

    $x++;
    echo"

<td class='center'>
    <input id='hap' type='checkbox' name='c_$x' value='$a[comment_id]'>
</td>";

}

但它只是在第一个循环中选择/检查一个数据,而没有选择另一个数据

任何人都知道它有什么问题吗?

4 个答案:

答案 0 :(得分:3)

ID是独一无二的。如果页面上有多个ID,则只使用第一个。如果您在页面上需要多个内容,则需要使用Class。

答案 1 :(得分:0)

试试这段代码。将id更改为class

 echo"

<td class='center'>
    <input class='hap' type='checkbox' name='c_$x' value='$a[comment_id]'>
</td>";

在js

$(function () {
       $('#select-all').click(function (event) {

           if($(this).is(':checked')) {
        $(".hap").attr('checked', 'checked');
    } else {
        $(".hap").removeAttr('checked');
    }


}); 

答案 2 :(得分:0)

试试这个:

function actualizarSeleccion(){
   $('.hap').each(function () {    
       this.checked = document.getElementById("select-all").checked;; 
   });
}    

<input type='checkbox' id='select-all' onchange="actualizarSeleccion()"><label for='select-all'>Delete all</label>

答案 3 :(得分:0)

也许你喜欢这样:

$(function () {
     $('#select-all').click(function() {
          $(".hap").prop("checked", this.checked);
     });
});
  • 没有设置无用的变量
  • 不使用每个方法(而是在jquery集合对象中使用prop)