Question

I would like to be able to style all of the checkboxes on a page using the jQuery UI buttons. However, many of the buttons are unlabeled. Is there a way I could do something like this:

$(".unlabeled-checkbox").append("<label> </label>").button();

But also properly fill out the "for" attribute of the label?

Was it helpful?

Solution 2

You may use jQuery's "wrap" function to wrap all your checkboxes:

$(".unlabeled-checkbox").wrap("<label></label>");

That will produce HTML:

<label>
    <input class="unlabeled-checkbox" type="checkbox" value="a" />
</label>
<label>
    <input class="unlabeled-checkbox" type="checkbox" value="b" />
</label>

If you wrap <label> around your <input> you don't need the "for" attribute. Clicking on the label will trigger click on the inner checkbox.

OTHER TIPS

You can pass the wrap() method a function to execute, try this:

$('.unlabeled-checkbox').wrap(function() {
    return $('<label></label>').attr('for', $(this).prop('name'));
});

Within the function, this will refer to the current .unlabeled-checkbox element in the array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top