Monday 8 December 2008

checkboxes for multiple items

I am doing an interface where I want to list a bunch of things (index) and have a checkbox next to each of them. Then, using a button, edit or show all those selected items.
I am always running into this problem of checkboxes (maybe I am just stupid) so I spent some time and figured out a way that works for me. There are probably other solutions, but here is what I do:

First, in the index.html I have this javascript code:

<% content_for :javascript do %>
<script type="text/javascript" charset="utf-8">
/* <![CDATA[ */
function editDevices() {
var device_count = document.getElementsByName('device[]').length;
var total="";
for(var i=0; i < device_count; i++){
if(document.forms['group_edit'].elements['device[]'][i].checked) {
if (total.length > 0) {
total += ","
}
total +=document.forms['group_edit'].elements['device[]'][i].value;
}
}

new Ajax.Request('<%= group_edit_devices_path %>', {
parameters: {
authenticity_token: encodeURIComponent('<%=form_authenticity_token%>'),
device_ids: total
}
}
);
}

function showDevices() {
var device_count = document.getElementsByName('device[]').length;
var total="";
for(var i=0; i < device_count; i++){
if(document.forms['group_edit'].elements['device[]'][i].checked) {
if (total.length > 0) {
total += ","
}
total +=document.forms['group_edit'].elements['device[]'][i].value;
}
}

new Ajax.Request('<%= group_show_devices_path %>', {
parameters: {
authenticity_token: encodeURIComponent('<%=form_authenticity_token%>'),
device_ids: total
}
}
);
}
/* ]]> */
</script>
<% end %>


Then I have the table of devices:

<table border="0" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th>&nbsp;</th>
<th>Uid</th>
<th>Name</th>
<th>Ip</th>
<th># Displays</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="5">
<ul class="tabs">
<li><%= link_to_function "Show", "showDevices()" %></li>
<li><%= link_to_function "Edit", "editDevices()" %></li>
<li><%= link_to "Delete" %></li>
</ul>
</td>
</tr>
</tfoot>
<tbody>
<% for device in @devices %>
<tr>
<td><%= check_box_tag("device[]", device.id, false, :id => "device_#{device.id}") %></td>
<td><%=link_to_remote h(device.uid), :url => formatted_device_path(device, :js), :method => "get" %></td>
<td><%=h device.name %></td>
<td><%=h device.ip %></td>
<td><%= device.displays.count %></td>
</tr>
<% end %>
</tbody>
</table>


The result is that my ajax function will be called with a comma separated list of the ids of the selected devices.

No comments: