[英]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>')
}
});
});
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.