javascript - 如何从复选框收集选中的值 Jquery

标签 javascript jquery html

我目前正在尝试收集特定复选框的值并将它们附加到另一个列表中。

这是我的 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/

相关文章:

javascript - 如何读取 Meteor 后端的文件?

javascript - 用时间跨度计算每天分配的有效方法

javascript - 打字完成后提交表格吗?

php - 变量不从 PHP 中的数据库更新

JavaScript sleep /等待,然后再继续

javascript - 触发google plus上加号按钮的点击事件

jquery - 使用 jquery 识别是否有子菜单

javascript - 如何使用 JQuery 以编程方式单击特定 div 上的特定 X-Y​​ 位置?

html - 使用 CSS3 设置多个背景图像的样式

javascript - 找不到解决方案 : load images to div based on page location