2015-11-21 152 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屬性值在文檔中必須是唯一的。改用類。

相關問題