Reputation: 125
Hi I'm trying to "check all or deselect all" check boxes in my rails app. it does working when I use the checkbox and JS. But, I also want the user the have the same function with links as well. So, when the click on the link it will "check all or deselect all" checkboxes.
Thanks,
<!-- Split button -->
<div class="btn-group">
<button type="button" class="btn btn-warning"><input type="checkbox" id="selecctall" value="selectAll"></button>
<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a id="selectAll" title="Click to do something" href="#" onclick="check();return false;">Select All</a></li>
<li><a id="selectAll" title="Click to do something" href="#" onclick="uncheck();return false;">None</a></li>
</ul>
</div>
<% @users.each do |user| %>
<tr class="<%= cycle("even", "odd") %>">
<td><input id= "user_id_<%="#{user.id}"%>" name="user_ids[]" value=<%= user.id %> type="checkbox" class="checkbox1"></td>
<td><%= user.full_name %></td>
<td><%= user.email %></td>
<td>
<% end %>
<% content_for :javascripts do %>
<script >
function check() {
if(document.getElementById("selecctall").checked = true;
}
function uncheck() {
document.getElementById("selecctall").checked = false;
}
$(document).ready(function() {
$('#selecctall').click(function(event) {
if(this.checked) {
$('.checkbox1').each(function() {
this.checked = true;
});
}else{
$('.checkbox1').each(function() {
this.checked = false;
});
}
});
});
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
</script>
Upvotes: 1
Views: 995
Reputation: 135
As EyasSH stated you should never use duplicate IDs as it is a terrible practice and invalid. This is why $('#selectall')
returns only one single element. BUT you can change the selector to make it find all instances of the duplicate IDs by changing it to $('[id="selectall"]')
Upvotes: 1
Reputation: 3769
Note that the ID of an element must be unique.
When looking up an element by ID, JavaScript will match only a single element, as it assumes that the contract that IDs are unique is respected.
If you have two links, one for "select all" and one for "select none", give each of them different IDs (or class names), and have a different $(...).click(function() { ... });
callback for each of them.
For one, it simply does the check
, and for another, it does the uncheck
.
Notice how your click
callback has an if (this.checked) ...
part. This works if this
is a checkbox, which it no longer is. Depending on which link is pressed, you already know if you intend to check or uncheck, which is why separate callbacks for each link makes sense.
Upvotes: 1