I’m trying to create a check all / uncheck all function for a series of
check boxes. Seems easy, but for some reason the brackets used in the
check_box_tag don’t play well with javascript functions
Here’s a real basic example of what I’m trying to do:
View:
<%= form_tag({:action => “delete_contact_add_campaign”}, {:method =>
:post,
:name => “contact_list”}) %>
<% for contact in @contacts %>
<%= check_box_tag(‘delete_contact[]’, contact.id) -%>
<%= check_box_tag(‘add_to_group[]’, contact.id) -%>
<% end %>
<%= submit_tag ‘Add to Group’, :name => ‘add_to_group’ %>
<%= submit_tag ‘Delete from list’, :name =>
‘delete_selected_contacts’ %>
<%= end_form_tag %>
…but that won’t check any of the boxes. If I remove the brackets from
the
check_box_tag for delete_contact and add_to_group all the check boxes
get
checked, but then I don’t get the array of ids in
params[‘delete_contact’]
or params[‘add_to_group’]
Forgive me for the javascript noob question. Your toggleAll(name)
function
is probably what I should be using. I tried using it and I still get a
syntax error:
function toggleAll(name)
{
boxes = document.getElementsByClassName(name);
for (i = 0; i < boxes.length; i++)
if (!boxes[i].disabled)
{ boxes[i].checked = !boxes[i].checked ; }
}
function setAll(name,state)
{
boxes = document.getElementsByClassName(name);
for (i = 0; i < boxes.length; i++)
if (!boxes[i].disabled)
{ boxes[i].checked = state ; }
}
Pretty sure these will work with controls that have ‘[]’ in their
names.
JavaScript syntax says that you’re trying to treat delete_contact as an
object and look up the property with the name …oops, you didn’t
supply a name. Hence the error.
In JavaScript, as in Lua, you can reference any property of any object
in two ways:
Using standard ‘dot’ notation, as you have above:
alert( foo.bar );
Using bracket notation (as the system thought you were trying to
do):
alert( foo[ “bar” ] );
This latter method is useful when you have the name of the property you
want stored in another variable:
var prop = “bar”;
alert( foo[ prop ] );
or (as in your case) when the name of the property is not a valid
JavaScript identifier:
checkAll( document.contact_list[ “delete_contact[]” ] );