devc2 February 2016

table cell input returns as undefined

I am using jquery 2 I need to populate a multidimensional array with values in a table

Here is my code (First column is hidden)

html:

<table  id="datatab"  border="1">
    <tbody>
        <tr role="row" class="odd">
            <td class="sorting_1" style="display: none;">2087971</td>
            <td>1</td>
            <td>1</td>
            <td>aaaa</td>
            <td>John Smith</td>
            <td><input type="text"  name="value1" value="1"></td>
            <td><input type="text"  name="value2" value="2"></td>
            <td><input type="text"  name="value3" value="3"></td>
            <td></td>
         </tr>
        <tr role="row" class="even">
            <td class="sorting_1" style="display: none;">2087972</td>
            <td>2</td>
            <td>2</td>
            <td>bbbb</td>
            <td>Peter Parker</td>
            <td><input type="text"  name="value1" value="4"></td>
            <td><input type="text"  name="value2" value="4"></td>
            <td><input type="text"  name="value3" value="4"></td>
            <td></td>
        </tr>
    </tbody>
</table>
<button id="GetData">Get data</button>

jquery:

<script type="text/javascript">

    $("#GetData").click(function (event) {
        debugger;
        event.preventDefault();
        var TableData = new Array();
        $('#datatab tbody tr').each(function (row, tr) {
            TableData[row] = {
                "id": $(tr).find('td:eq(0)').text()
                , "value1": $(tr).find('td:eq(5)').find("input").value
                , "value2": $(tr).find('td:eq(6)').find("input").value
                     

Answers


Rory McCrossan February 2016

You need to use the val() method of the jQuery objects, as they do not have value property like the underlying DOMElements. Also note that you can use map() to build the array. Try this:

$("#GetData").click(function(e) {
    e.preventDefault();
    var tableData = $('#datatab tbody tr').map(function(row, tr) {
        var $row = $(tr);
        return {
            id: $row.find('td:eq(0)').text(),
            value1: $row.find('td:eq(5) input').val(), 
            value2: $row.find('td:eq(6) input').val(),
            value3: $row.find('td:eq(7) input').val()
        }
    }).get();

    // work with tableData here...
});

Working example

Post Status

Asked in February 2016
Viewed 1,154 times
Voted 7
Answered 1 times

Search




Leave an answer