简体   繁体   中英

How can I add items to a list when a checkbox is checked in jQuery?

I have a list of checkbox and I want that when it's checked, the label or the value of the checkbox will be added in a list.

The fiddle below, when the checkbox is checked/unchecked, it adds 'on' to the list.

Here's a sample fiddle

$('.cb').click(function() {
  var cbVal = $("input[type='checkbox']").val();
  $('ul').append('<li>'+cbVal+'</li>')
});

Up on clicking, you can iterate the checkboxes, see checked state and update the list.

$('.cb').click(function() {
$('ul').html("");
$(".cb").each(function(){
    if($(this).is(":checked")){
         $('ul').append('<li>'+$(this).val()+'</li>')
    }
});
});

Following is the updated fiddle .

You can use this inside event handler to be able to check what checkbook was selected, also it is better to use change event here.

$('.cb').change(function() {
  var cbVal = this.checked ? 'on ' : 'off ';
  cbVal += $('[for='+this.id+']').text ();
  $('ul').append('<li>'+cbVal+'</li>');
});

To be able to remove li from ul add id to it when appending $('ul').append('<li id="item-' + this.id + '">' +cbVal+'</li>');

Try this:

$(document).ready(function () {
  $('.cb').click(function () {
    var  szId=$(this).attr('id');
    var cbVal = $('label[for=' + szId + ']').text();
    $('ul').append('<li>' + cbVal + '</li>')
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM