开发者

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 ja开发者_开发知识库vascript I always feel like I'm very inefficient. This also doesn't take into account boxes already set to check on page load...


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜