获取复选框值并显示它们

Getting checkbox value and show them

本文关键字:显示 复选框 获取      更新时间:2023-09-26

我想显示复选框选中项目的值。这是我的睡衣。控制台中未定义。如何解决这个问题。

http://jsfiddle.net/bmtx4ykc/

$(document).ready(function() {
  $("#checkAll").change(function() {
    $("input:checkbox").prop('checked', $(this).prop("checked"));
  });
  $('#submitButton').click(function() {
    var values = $("#add input[name=chkboxName]:checked").map(function() {
      row = $(this).closest("tr");
      return {
        id: $(this).val(),
        name: $(row).find("#name").text(),
        quantity: $(row).find("#quantity").text()
      }
    }).get();
    $('#result').append(values.name);
    console.log(values.name);
  });
});

这是因为map()方法正在返回一个对象数组。

您正在获取undefined,因为您正试图访问数组的name属性。您需要访问数组中对象的name属性。

例如,如果选择了第三行,则values[0]将返回以下内容:

console.log(values[0]);
// Object {id: "2", name: "Orange", quantity: "6"}
console.log(values[0].name);
// "Orange"

您可以简单地迭代数组中的项,以便记录每个对象的name属性:

更新示例

values.forEach(function (row) {
    console.log(row.name);
});

附带说明一下,id属性值在文档中必须是唯一的。请改用类。

values类似于一个对象数组,使用jquery each显示数据:

$(document).ready(function(){
	$("#checkAll").change(function () {
		 $("input:checkbox").prop('checked', $(this).prop("checked"));
	});
    $('#submitButton').click(function(){
        var values = $("#add input[name=chkboxName]:checked").map(function()
                     {
                         row = $(this).closest("tr");
                         return { 
                             id : $(this).val(),
                             name     : $(row).find("#name").text(),
                             quantity       : $(row).find("#quantity").text()
                     }
                  }).get();
        
        // empty the results div then loop the values and append the name
        $('#result').empty();
        $(values).each(function(){ $('#result').append(this.name + '<br />');});
       
    });
});
		table{
		    border-collapse: collapse;
		}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" id="add">
    <tr>
        <th><input type="checkbox" id="checkAll" value="All"></th>
        <th>Name</th>
        <th>Quantity</th>
    </tr>
    <tr>
        <td><input type="checkbox" name="chkboxName" value="1"></td>
        <td id="name">Apple</td>
        <td id="quantity">5</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="chkboxName" value="2"></td>
        <td id="name">Orange</td>
        <td id="quantity">6</td>
    </tr>
</table>
<button id="submitButton">Show in table</button>
        <div id="result"></div>