简体   繁体   English

在jQuery中选中复选框时,如何将项添加到列表中?

[英]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. 下面的小提示,当选中/取消选中复选框时,它会在列表中添加“on”。

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. 您可以使用this内部事件处理程序来检查选择的支票簿,也可以在此处使用change事件。

$('.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>'); 为了能够从ul删除li ,在追加$('ul').append('<li id="item-' + this.id + '">' +cbVal+'</li>');时添加$('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>')
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我怎样才能添加 '<input type="checkbox" checked> ' 属性到所有使用 jQuery 动态创建的列表项? - How can I add a '<input type="checkbox" checked>' attribute to all li dynamically created list items using jQuery? 我如何将选中复选框的数量添加到此jQuery / JS代码 - How can i add the numbers of checked checkbox to this jquery / js code 选中复选框时如何将字符串添加到数组? - How can I add a string to an array when a checkbox is checked? 如何在下拉列表/选择列表列表中添加复选框选中的项目 - How to add checkbox checked items in Dropdown/selectlist list 选中复选框时如何使列表项的文本变灰? - How to gray out the text of the list items when their checkbox is checked? 选中另一个复选框后,如何检查该复选框? [JavaScript的] - How can I check a checkbox when another checkbox is checked? [JavaScript] 如果选中了一个复选框,我如何检查 JQuery,如果选中,则将 class 添加到父 label? - How can I check with JQuery if a checkbox is checked and if so add a class to the parent label? 使用JQuery选中复选框时,如何隐藏然后显示多个Div - How can I hide then show multiple Divs when checkbox is checked using JQuery 如何在 javascript/jquery 中获得选中的复选框标题值? - How can i get a checked Checkbox title value in javascript/jquery? 我如何将项目添加到选定的附加列表 jquery - how can i add items to selected append list jquery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM