Register now and start sharing your code snippets.
-->

Populating a table with n checkbox fields

Ruby posted 8 months ago by christian

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

   1  x  x  x  x
   2  x  x  x  x
   3  x  x  

This can be achieved with the following code:

   1  <table>
   2  <% 
   3  	from = 0
   4  	to   = checkboxes.size
   5  	cols = 4
   6  
   7  	from.step(to, cols) do |i| 
   8  %>
   9  	<tr>
  10  	<% for checkbox in checkboxes.slice(i..i + (cols -1)) %>
  11     		<td><input type="checkbox" id="<%= checkbox.name %>" name="column" value="<%= checkbox.value %>"/> <label for="<%= column.name %>"><%= column.name%></label></td>
  12  	<% end %>
  13  	</tr>
  14  <% end %>
  15  </table>

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

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

Tagged table, checkbox, populating