dhornbein
dhornbein

Reputation: 214

JQuery: add/remove html based on checkbox state

<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...

Upvotes: 1

Views: 3816

Answers (2)

user113716
user113716

Reputation: 322492

I'd have them on the page from the beginning, and then just show/hide them using the filter()(docs) method with this.id and the toggle()(docs) method with this.checked, while placing the most recently clicked one at the bottom of the list using the appendTo()(docs) 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) event on each element immediately after they've been assigned to set the initial state of the list items.

Upvotes: 0

user193476
user193476

Reputation:

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);
}

Upvotes: 4

Related Questions