获取所有选中输入的标签并附加到html(每个标签) [英] Get labels for all checked inputs and append to html (for each)
本文介绍了获取所有选中输入的标签并附加到html(每个标签)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在页面上有多个带有标签的复选框.对于每个选中的复选框,我想将标签附加到div(以逗号分隔)上.取消选中其中一个复选框后,我想从div中删除该特定标签.复选框的数量可以是可变的.
I have multiple checkboxes with labels on a page. For each checkbox that is checked I want to append the label to a div (comma separated). When one of the checkbox is unchecked I want to remove that specific label from the div. The number of checkboxes can be variable.
到目前为止我所拥有的:
What I have so far:
$("input:checkbox").click(function() {
var selected = $("label[for='" + this.id + "']").text() + ',';
$("p").html(selected);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
<input id="checkbox1" type="checkbox" />
<label for="checkbox1">checkbox label</label>
使用此代码,我可以将选中的复选框标签之一附加到html.
With this code I can append one of checked checkboxes labels to the html.
推荐答案
您可以 .filter()
:checked
复选框,然后使用
You can .filter()
:checked
checkboxes then use .map()
and get the label text in an array.
//Cache selectors
var elem = $("input:checkbox");
//Bind change event
elem.change(function() {
var selected = elem
.filter(':checked') //Filter only checked checkboxes
.map(function() {
return $("label[for='" + this.id + "']").text();
})
.get(); //Get array
$("p").html(selected.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
<input id="checkbox1" type="checkbox" />
<label for="checkbox1">checkbox label</label>
<br/>
<input id="checkbox2" type="checkbox" />
<label for="checkbox2">checkbox label 2</label>
这篇关于获取所有选中输入的标签并附加到html(每个标签)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文