I have list of restaurant cuisines (HABTM) - when the user adds a restaurant, they choose from all the checkboxes of cuisines.
The checkbox inputs are set to float:left; with padding/margins... etc and all looks good - a nice grid of checkboxes.
Question/Problem: The checkboxes show up alphabetically, but not in the way a user would expect - they're left to right in repeating rows (like you'd expect by making them all float).
How can I get them to be alphabetical, but in vertical columns? So alphabetically, you'd read Top to Bottom, then go to the next column.
I could do this just find w/ just normal PHP, but in CakePHP, my call to show the checkboxes is just:
<?php echo $this->Form->input('RestaurantCuisine', array('multiple'=>'checkbox')); ?>
ADDITION:
JS FIDDLE HERE (html is mostly un-editable since it's being generated by CakePHP - can edit the CakePHP echo though if needed - but that can't be in the fiddle)
Based on the comments, I've created a hopefully acceptable jQuery solution.
See: http://jsfiddle.net/svRmL/
var $element = $('#cuisines');
var $elementWidth = $element.find(' > .checkbox').outerWidth(true),
elementCount = $element.find(' > .checkbox').length,
$boxes = $element.find(' > .checkbox');
/* just for debug */
$boxes.each(function(i) {
$(this).find('label').html(i);
});
//set resize function
$(window).resize(function() {
var perRow = Math.floor($element.width() / $elementWidth),
i, j, $thisColumn, inc;
$boxes.appendTo($element); //move elements out of columns from previous resize
$('.tempColumn').remove(); //destroy old columns
for (i = 0; i < perRow; i++) {
$thisColumn = $('<div class="tempColumn" />').appendTo($element).css({
width: $elementWidth,
float: 'left'
});
inc = Math.ceil(elementCount / perRow);
for (j = inc * i; j < inc * (i + 1); j++) {
$boxes.eq(j).appendTo($thisColumn);
}
}
}).resize(); //trigger resize function immediately
来源:https://stackoverflow.com/questions/6114173/how-to-make-cakephps-habtm-checkboxes-alphabetical-top-to-bottom-in-columns