简体   繁体   中英

How to grab data from table with divs and inputs inside cells?

I am still new to js and jQuery. How would I iterate through the table and grab data from each cell (the date, and input "from" and "to")?

<table class="table table-striped table-bordered table-hover table-condensed" id="entryTable">
    <thead>
        <th>Date</th>
        <th>First Shift</th>
        <th>Second Shift</th>
    </thead>
    <tbody>
        <tr>
            <td>2/1/2016</td>
            <td>
                <div id="time" class="form-group">
                    From: <input type="text" id="start01"> 
                    To: <input type="text" id="end01">
                </div>
            </td>
            <td>
                <div id="time" class="form-group">
                    From: <input type="text" id="start02" > 
                    To: <input type="text" id="end02">
                </div>
            </td>
        </tr>
    </tbody>
</table>

in javascript you can use the method document.getElementById("tagId") for example in your case document.getElementById("time") or you can use document.getElementByClassName("tagClassName") or document.getElementByTagName("TagName") and each of them returns an array of dom elements in JQuery library it's so similar to css selectors for example

$("#elementId") to select an element by its id 
$(".className") to select an elements by their class name 
$("tagname") like $("p") to select all the p tags in the dom 
$("div p") to select the p tags which in a div tag 
and for example in your code you can grape a th element in your table using a selector like that $("#entryTable > thead th:nth-child(2)") 

and I think that

Here Is a Jsfiddle I built for you JsFiddle To Get table values

And the code I used is

  var date = $('#entryTable').find('tbody td:eq(0)').text();

  var From01 = $('#entryTable').find('tbody td:eq(1) input:eq(0)').val();
  var To01 = $('#entryTable').find('tbody td:eq(1) input:eq(1)').val();

  var From02 = $('#entryTable').find('tbody td:eq(2) input:eq(0)').val();
  var To02 = $('#entryTable').find('tbody td:eq(2) input:eq(1)').val();

In the Fiddle I have put a button to fetch the value on click of the button, I am displaying the values in alert, you can change the code according to your requirement - List item

EDIT: To loop through all the td's you can do this

$.each($('#entryTable').find('tbody td), function(){
         var currentTdOfLoop = $(this);
        //do your stuff here
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM