Question: ```
<ul id="list">

</ul>
<input type="checkbox" id="item1" name="item one" />
<input type="checkbox" id="item2" name="item two" />
<input type="checkbox" id="item3" name="item three" />
<input type="checkbox" id="item4" name="item four" />

```

I need to add checked items to the `#list` as li's in this format:

```
<li class="CHECKBOX ID">CHECKBOX NAME</li>

```

Here's what I'm currently working on:

```
$('input[type=checkbox]').change(function () {

if($(this).is(':checked')){
var checkboxId = $(this).attr('id');
var checkboxName = $(this).attr('name');

$('#list').append('<li class="' + checkboxId  + '">' + checkboxName  + '</li>');
} else {
$('#list .' + checkboxId).remove();
}

```

When ever I work with javascript I always feel like I'm very inefficient. This also doesn't take into account boxes already set to check on page load...

Answer: 
What you should do is make a function, e.g. `toggleListCheckbox` and call that when the page loads and also on the event.

```
function toggleListCheckbox() {
    if($(this).is(':checked')) {
        var checkboxId = $(this).attr('id');
        var checkboxName = $(this).attr('name');
        $('#list').append('<li class="' + checkboxId  + '">' + checkboxName  + '</li>');
    } else {
        $('#list .' + checkboxId).remove();
    }
}

$(document).ready(function () {
    $('input[type=checkbox]').each(toggleListCheckbox).change(toggleListCheckbox);
}

```
I'd have them on the page from the beginning, and then just show/hide them using the [`filter()`*(docs)*](http://api.jquery.com/filter/) method with `this.id` and the [`toggle()`*(docs)*](http://api.jquery.com/toggle/) method with `this.checked`, while placing the most recently clicked one at the bottom of the list using the [`appendTo()`*(docs)*](http://api.jquery.com/appendto/) method.

**Example:** <http://jsfiddle.net/NBQpM/3/>

*html* 

```
<ul id="list">
    <li class="item1">item one</li>
    <li class="item2">item two</li>
    <li class="item3">item three</li>
    <li class="item4">item four</li>
</ul>

```

*js*

```
var listItems = $('#list li'); 

$('input[type=checkbox]').change(function() {
    listItems.filter('.' + this.id).appendTo('#list').toggle(this.checked);
}).change();

```

This also triggers the [`change()`*(docs)*](http://api.jquery.com/change/) event on each element immediately after they've been assigned to set the initial state of the list items.