Reputation: 51941
In a form_tag
, there is a list of 10 to 15 checkboxes:
<%= check_box_tag 'vehicles[]', car.id %>
How can I select-all (put a tick in every single) checkboxes by RJS? Thanks
EDIT: Sorry I didn't make my question clear. What I meant to ask is how to add a "Select/Un-select All" link in the same page to toggle the checkboxes.
Upvotes: 1
Views: 771
Reputation: 324567
The following function will toggle the checkedness of all checkboxes inside a particular DOM element (for example, a <form>
element):
function toggleAllCheckBoxes(el) {
var inputs = el.getElementsByTagName("input");
var input, checked = false, i, len;
// Check whether all the checkboxes are all already checked.
// If so, we uncheck all of them. Otherwise, we check all of them.
for (i = 0, len = inputs.length; i < len; ++i) {
input = inputs[i];
if (input.type == "checkbox" && !input.checked) {
checked = true;
break;
}
}
// Now check or uncheck all of the checkboxes
for (i = 0, len = inputs.length; i < len; ++i) {
input = inputs[i];
if (input.type == "checkbox") {
input.checked = checked;
}
}
}
var form = document.getElementById("your_form_id");
toggleAllCheckBoxes(form);
Upvotes: 0
Reputation: 77778
Try this:
<%= check_box_tag 'vehicles[]', car.id, {:checked => "checked"} %>
You can use Tim Down's solution for vanilla javascript solution. If you are using jQuery, you can try something like this:
<script>
$(document).ready(function(){
// select all
$(".checkboxes a[rel=all]").click(function(){
$(this).siblings("input:checkbox:not(:checked)").attr({checked: true});
});
// select none
$(".checkboxes a[rel=none]").click(function(){
$(this).siblings("input:checkbox:checked)").removeAttr("checked");
});
});
</script>
<div class="checkboxes">
<input type="checkbox" value="foo" /> Foo
<input type="checkbox" value="bar" /> Bar
<input type="checkbox" value="baz" /> Baz
select
<a href="#" rel="all">all</a> |
<a href="#" rel="none">none</a>
</div>
Upvotes: 1