checkbox snippets

Populating a table with n checkbox fields

Tagged checkbox, table, enumerator, in_groups_of, populating  Languages ruby

Let's say you have 10 checkboxes and you want to display 4 per line as shown here:

x  x  x  x
x  x  x  x
x  x

This can be achieved with the following code:

<table>
<% 
    from = 0
    to   = checkboxes.size
    cols = 4

    from.step(to, cols) do |i| 
%>
    <tr>
    <% for checkbox in checkboxes.slice(i..i + (cols -1)) %>
        <td><input type="checkbox" id="<%= checkbox.name %>" name="column" value="<%= checkbox.value %>"/> <label for="<%= column.name %>"><%= column.name%></label></td>
    <% end %>
    </tr>
<% end %>
</table>

If you're using Rails you can also use the built in method described here.

%w(1 2 3 4 5 6 7).in_groups_of(3) {|g| p g}
["1", "2", "3"]
["4", "5", "6"]
["7", nil, nil]

You can also use the Enumerator class

Getting the state of checkboxes with jQuery

Tagged checkbox, jquery  Languages javascript

The following code will loop through all selected (checked) checkboxes and collect their values in an array:

var selected = [];
$('#select-columns input[@type=checkbox]').filter(':checked').each(function () {
    selected.push(this.value);
});
console.log(selected);

More examples can be found here