我有三个复选框按钮。我希望它具有这样的功能,当我单击“全选”时,要选中所有复选框,当我单击“支票公司”时,只需要选中公司,当我在自由职业者上选择时,只希望选中“自由职业者”复选框。现在,第一个复选框可以正常工作,所有复选框都处于选中状态和未选中状态,而其他两个复选框则无法工作。请帮忙。
$('#check_all').on("click", function(){
var cbxs = $('input[type="checkbox"]');
cbxs.prop("checked", !cbxs.prop("checked"));
});
$('#mycompanies').click(function(){
var select_all = (this.value === 'Select All');
$('input:checkbox').attr('checked', select_all);
this.value = (select_all) ? 'Deselect All' : 'Select All';
});
$('#myfreelancers').click(function(){
var select_all = (this.value === 'Select All');
$('input:checkbox').attr('checked', select_all);
this.value = (select_all) ? 'Deselect All' : 'Select All';
});
<button type="button" id="check_all" class="btw">Check all/Uncheck all</button>
<button type="button" id="mycompanies" class="mycompanies">Check all companies</button>
<button type="button" id="myfreelancers" class="myfreelancers">Check all freelancers</button>
这里是我的自由职业者的复选框
<% @m_freelancers.each do |freelancer| %>
<tr>
<td><%=check_box_tag 'selected_freelancers[]', freelancer.id%>
<td><%= freelancer.email %></td>
<tr/>
<% end %>
公司复选框
<% @m_companies.each do |company| %>
<tr>
<td><%=check_box_tag 'selected_companies[]', company.id%></td>
<td><%= company.user.email %></td>
</tr>
<% end %>
答案 0 :(得分:1)
使用选择器[name="myElementName"]
通过名称查找元素,然后进行相应检查。因为您的元素是HTML“数组”([]
),所以您还需要将其包括在选择器中。
您可能要考虑使用一个类代替它,可能会更干净一些-但此选择器会很好。
// Check all if all is unchecked - remove all checks if one or more is checked
$('#check_all').on("click", function(){
var cbxs = $('input[type="checkbox"]');
cbxs.prop("checked", !cbxs.prop("checked"));
});
$("#mycompanies").on("click", function() {
var companyCheckboxes = $('[name="companies[]"]');
companyCheckboxes.prop("checked", true);
});
$("#myfreelancers").on("click", function() {
var freelancerCheckboxes = $('[name="freelancers[]"]');
freelancerCheckboxes.prop("checked", true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="check_all" class="btw">Check all/Uncheck all</button>
<button type="button" id="mycompanies" class="mycompanies">Check all companies</button>
<button type="button" id="myfreelancers" class="myfreelancers">Check all freelancers</button>
<br />
<br />
<input type="checkbox" name="freelancers[]" /> Freelance 1<br />
<input type="checkbox" name="freelancers[]" /> Freelance 2<br />
<input type="checkbox" name="freelancers[]" /> Freelance 3<br />
<input type="checkbox" name="freelancers[]" /> Freelance 4<br />
<input type="checkbox" name="companies[]" /> Company 1<br />
<input type="checkbox" name="companies[]" /> Company 2<br />
<input type="checkbox" name="companies[]" /> Company 3<br />
<input type="checkbox" name="companies[]" /> Company 4