2013-09-26 130 views
0

在我的html页面中,我想动态插入复选框,并且我希望在顶部有一个主复选框,所以如果选中,那么所有动态创建的复选框都会被选中,如果未选中,那么所有动态的变得没有选中。我有这样的代码:Jquery复选框toggeling不起作用

<script type="text/javascript"> 
    $(function() { 
     $("#selectAll").click(function() { 
      var checked = $(this).prop('checked'); 
      $(".profilebox").attr("checked", checked); 
     }); 
    }); 
</script> 

主复选框

<input id="selectAll" type="checkbox" name="selectall" value="All"> 

其他复选框:(获得使用这个PHP代码在一个循环中插入)

<input type='checkbox' class='profilebox' name='select' value='{$member_id}'> 

但是它不正常。如果我点击主人,那么他们都会被检查。如果我再次点击它,那么所有的都会被取消选中,然后如果我再次点击它们,它们仍然未被选中。

有谁知道这个问题?

感谢

回答

6

使用prop instead of attr,设置元素的属性保证比设置元素的属性工作。 jquery的老版本,没有道具,attr用于执行两者的工作,后来道具被引入,并设置像这样的属性prop服务最好。

$(function() { 
     $("#selectAll").click(function() { 
      $(".profilebox").prop("checked", this.checked); 
     }); 
    }); 
+1

此作品很好,谢谢。 – omega

+1

@ mega欢迎您。 – PSL

1

需要使用.prop()设置检查属性,而不是.attr()

$(".profilebox").prop("checked", this.checked); 

例:

$(function() { 
    //cache the selector result 
    var $profileboxes = $(".profilebox"); 
    $("#selectAll").click(function() { 
     $profileboxes.attr("checked", this.checked); 
    }); 
}); 

阅读:Attributes vs. Properties

1

使用.prop()

$(".profilebox").prop("checked", this.checked); 

现在你的代码变得

$(function() { 
    $("#selectAll").click(function() { 
     $(".profilebox").prop("checked", this.checked); 
    }); 
}); 

$(ELEM).prop( “选中”)真(布尔)将与复选框 状态

$(ELEM).attr改变(“checked”)(1.6)“checked”(String)初始状态 复选框;不改变$(ELEM).attr( “选中”)

(1.6.1+) “选中”(字符串)将与复选框状态

$(ELEM).attr( “选中”)改变(pre-1.6)true(布尔型)更改为 复选框状态