Friday, October 14, 2016

How to get a nested td value in Jquery


I have a difficult task at hand to get the value of a "td" which is generated by Keno Grid and its really driving me crazy due to time constraint at client end. Following is the solution.

Main div has id which gave me hope

the mock structure is below

 <div id="mainDiv">
        <div>
            <div class="div-class">
                <table>
                    <thead>
                        <tr>
                            <td>
                                header1
                            </td>
                            <td>
                                header 2
                            </td>
                        </tr>

                    </thead>
                </table>
            </div>
        </div>

        <div class="k-grid-content">
            <table border="1">
                <tbody>
                    <tr>
                        <td role="gridcell">column1</td>
                        <td role="gridcell">column2</td>
                    </tr>
                    <tr>
                        <td role="gridcell">columnn3</td>
                        <td role="gridcell">column4</td>
                    </tr>
                </tbody>
            </table>

        </div>
 
    </div>
<script>
 $('#mainDiv').on('click', '.div-class table tbody tr', function () {
                var value= $(this).find("td:first-child").text();
                });
</script>

1) First capture the click event of the div with id.
2) Access the div you require with class name "div-class".
3) Access the "table".
4) Access the "tbody"
5) Access the "tr"
then get the values you require. Our requirement was to have first column value.

No comments: