views:

67

answers:

2

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.

+1  A: 

Try this:

<%= check_box_tag 'vehicles[]', car.id, {:checked => "checked"} %>

Edit

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>
macek
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.
ohho
A: 

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);
Tim Down