您当前的问题是,作为一个整体,您正在选择复选框本身。您只想选择标签的值,而不想移动标签,而是将其复制到其他位置。
下面的代码使用jquery,该jquery在单击带有
id
#check
. 代码在每个复选框中循环
name=food
已检查,并附加
label
链接到列表的复选框的文本。
更新:
然后将此列表附加到一系列列表中,并根据请求添加一个标题。
我已经包含了一条线,如果你想在每个检查之间重置列表,你可以取消评论(否则你可以在列表中有相同版本的食物)。
如果你还需要什么,请告诉我。
希望有帮助
$("#check").click(function() {
// Uncomment the line below if you want to reset the list
// $("#lists .favourite-list").remove();
// Create variable to store list of foods if selected
tempList = ""
// Check if any foods are selected
$('[name="food"]:checked').each(function() {
// Get the text value of the label
// Should do this, rather than use 'for' value as it might differ
checkLabel = $("label[for='" + $(this).attr("value") + "']").text();
// Append a new list element
tempList = tempList + "<li>" + checkLabel + "</li>";
})
// Check if at least one food has been added
if (tempList != "") {
// Add ul wrappers to list and header.
tempList = "<div class='favourite-list'><p>Favourite Foods:</p><ul>" + tempList + "</ul></div>"
// Append new list
$("#lists").append(tempList);
}
});
#check {
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<legend>Pick the foods you like.</legend>
<input id="tacos" type="checkbox" name="food" value="tacos">
<label for="tacos">Tacos</label>
<input id="crepes" type="checkbox" name="food" value="crepes">
<label for="crepes">Crepes</label>
<input id="dumplings" type="checkbox" name="food" value="dumplings">
<label for="dumplings">Dumplings</label>
</fieldset>
<button id="check">Add to list</button>
<div id="lists">
</div>