我目前正在尝试收集特定复选框的值并将它们附加到另一个列表中。
这是我的 HTML 文件的一部分。
<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>
这是我目前使用的 javascript。
var $food = $('[name="food"]:checked');
$li.append($food);
首先,我没有得到我勾选的所有食物值。其次,我实际上只是附加复选框,并且复选框会从字段集中删除。我知道 $food
应该是一个列表,但我不太确定如何编写它。
最佳答案
您当前的问题是您正在选择整个复选框本身。您只想选择标签的值,并且不想移动它而是将其复制到其他地方。
下面的代码使用 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>
关于javascript - 如何从复选框收集选中的值 Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53890980/