checkbox snippets

Populating a table with n checkbox fields

Tagged table, checkbox, populating, enumerator, in_groups_of  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:

    from = 0
    to   = checkboxes.size
    cols = 4

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

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 jquery, checkbox  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 () {

More examples can be found here