Alphabetical Checkbox Input Type
I currently have a form containing checkboxes, however the text are not in alphabetical order. I have seen many examples for lists, not many for checkbox. http://jsfiddle.net/fG9qm
Solution 1:
You should wrap those textnodes in a label:
<form id="prac">
    <label><input type="checkbox" name="vehicle" value="Bike" /> Apple</label>
    <label><input type="checkbox" name="vehicle" value="Car" /> ABear</label>
</form>
Then sort the labels
var myform = $('#prac'),
    els    = $('label', myform).get(),
    sorted = els.sort(function(a, b) {
        return $(a).text().toUpperCase()
                   .localeCompare( $(b).text().toUpperCase() );
});
$.each(sorted, function(idx, itm) { 
     myform.append(itm); 
});
Solution 2:
You can wrap the inputs and their respective labels in containers to facilitate sorting.
<form>
    <div class="field-item">
        <input type="checkbox" name="vehicle" id="vehicle-bike" value="Bike" />
        <label for="vehicle-bike">Bee</label>
    </div>
    <div class="field-item">
        <input type="checkbox" name="vehicle" id="vehicle-car" value="Car" />
        <label for="vehicle-car">Apple</label>
    </div>
</form>
Then just adjust your sorting code to sort those containers based on the labels.
var $els = $('.field-item');
var $sorted = $($els.toArray().sort(function(a, b) {
    return $(a).find('label').text() > $(b).find('label').text()
}));
$els.each(function(i) {
    $(this).after($sorted.eq(i));
});
Post a Comment for "Alphabetical Checkbox Input Type"