views:

75

answers:

1

Hi

I have a un-ordered (ul) html list. Each li item has 1 or more classes attached to it. I want to go through this ul list and get all the (distinct) classes. Then from this list create a list of checkboxes who's value matches that of the class and also who's label matches that of the class. One checkbox for each class.

What is the best way to do this using JQuery?

Thanks

+2  A: 

Try this:

// get the unique list of classnames
classes = {};
$('#the_ul li').each(function() {
    $($(this).attr('class').split(' ')).each(function() { 
        if (this !== '') {
            classes[this] = this;
        }    
    });
});

//build the classnames
checkboxes = '';
for (class_name in classes) {
    checkboxes += '<label for="'+class_name+'">'+class_name+'</label><input id="'+class_name+'" type="checkbox" value="'+class_name+'" />';
};

//profit!
MDCore
You should check whether `this` is the empty string before adding it to the list, in case there are extra spaces in the class declaration.
Tgr
@Tgr done, thanks.
MDCore
You need to check against `''`. If you split by a space, you will never get a space, but `'a..b'.split('.')`will give `['a', '', 'b']`
Tgr
@Tgr thanks for the fix.
MDCore