David Edgar
David Edgar

Reputation: 505

Retrieve input values in td from table without id

I need to retrieve date from the generic input field. The number of how many date (input field) user can create in form is unknown by me, so I count them by rowCount.

I'm not enable to extract the value of field (Syntax error maybe).

N.B when I lunch my code I get: Cannot set property '0' of undefined

html code:

<div>
    <table id='dynamic_field_edit'>
         <tbody>
            <tr>
                <td>Date</td>
                <td><input type="text" placeholder="Enter date" /></td>
            </tr>
            <tr>
                <td>Date:</td>
                <td><input type="text" placeholder="Enter date" /></td>
            </tr>
         </tbody>   
    </table>
</div>

JS code :

var arrayDate = [];

    var rowCount = document.getElementById('dynamic_field_edit').rows.length;
    console.log(rowCount);

   var allInputs = document.querySelectorAll('input');
    for (let i = 0; i < allInputs.length; i++) {    
       arrayDate.push(allInputs[i].value);
    }
    console.log(arrayDate);

Edit:

After all suggested change it works, but it retrieve all values from input in document.

Upvotes: 0

Views: 185

Answers (3)

David Edgar
David Edgar

Reputation: 505

I find a way to achieve what I wanted to do by doing this.

@proggrock solution is also good for retrieving all input values in the document.

var arrayDate = [];

    var rowCount = document.getElementById('dynamic_field_edit').rows.length;
    console.log(rowCount);

    $("#dynamic_field_edit").find('input:text')
        .each(function() {
            arrayDate.push($(this).val());
        });
    console.log(arrayDate);

Upvotes: 0

proggrock
proggrock

Reputation: 3289

You just need to initialize your array:

var arrayDate = [];

EDIT:

Seems to work in this sample, can you compare to your code?

https://jsfiddle.net/emeLdecm/1/

(I added a button to fire off your JS, just to demonstrate)

Upvotes: 2

Alex Smith
Alex Smith

Reputation: 310

Y you use jQuery syntax in plain javascript?

Select your table via:

table = document.getElementById('dynamic_field_edit');

and that iterate:

for (var i = 0, row; row = table.rows[i]; i++) {
// do your stuff
};

Upvotes: 1

Related Questions