简体   繁体   English

按ID全选/取消全选页面中的所有复选框

[英]Select All/Deselect All checkboxes in a page by id

I have two blocks with checkboxes. 我有两个带有复选框的块。 I'm trying to check this particular checkboxes with JS. 我正在尝试使用JS选中此特定复选框。

 <%= hidden_field_tag "user[roles][]" %>
    <% User.valid_roles.map{|c| {name: c, id: User.mask_for(c)} }.each do |role| %>
      <%= check_box_tag "user[roles][]", role[:name], user.has_role?(role[:name]), id: "user_role_#{role[:id]}" %>
      <%= label_tag "user_role_#{role[:id]}", role[:name].to_s.titleize %><br/>
      <% end %>




$('#selectAll').click(function() {
   if(this.checked) {
       $(':checkbox').each(function() {
           this.checked = true;                        
       });
   } else {
      $(':checkbox').each(function() {
           this.checked = false;                        
       });
   } 
});

Something like this should work: 这样的事情应该起作用:

$('#selectAll').on('change', function(){
  var checkboxes   = $('input[id^="employer_"]');
  var checkedValue = !!this.checked;

  checkboxes.prop('checked', checkedValue);
});

Here is a fiddle to demonstrate: http://jsfiddle.net/f5nx0czv/ 这是演示的小提琴: http : //jsfiddle.net/f5nx0czv/

With jQuery you can set a property/attribute en masse, no need to iterate over the collection. 使用jQuery,您可以整体设置属性/属性,而无需遍历集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM