2015-11-21 99 views
2

我想显示复选框选中项目的值。 这是我的js。在控制台得到未定义。如何解决这个问题。获取复选框值并显示它们

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); 
    }); 
}); 
+1

ID必须是唯一的 –

回答

1

values类似于对象的数组,使用jQuery each来显示数据:

$(document).ready(function(){ 
 
\t $("#checkAll").change(function() { 
 
\t \t $("input:checkbox").prop('checked', $(this).prop("checked")); 
 
\t }); 
 
    $('#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 />');}); 
 
     
 
    }); 
 
});
\t \t table{ 
 
\t \t  border-collapse: collapse; 
 
\t \t }
<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>

+0

而不是'的.html( '')',你可以只使用['.empty()'方法](https://api.jquery.com/empty/)。 –

+0

感谢您指出老兄,我改变了这一点。 – KAD

2

这是因为map() method被返回对象的阵列。

因为您正在尝试访问数组的name属性,所以您得到undefined。您需要访问数组中对象的name属性。

例如,如果选择了第三排,然后values[0]将返回以下:

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

console.log(values[0].name); 
// "Orange" 

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

Updated Example

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

作为附注,id属性值在文档中必须是唯一的。改用类。

相关问题