Tom Tom - 3 months ago 6
Ajax Question

JQuery - Updating table contents

On my page I have a search input field and a table.

As the user searches the input is sent via AJAX to a backend page that returns the results. That is working fine.

What I'm trying to do is have the form start empty and then be populated by the returned results.

I've created the form as :

<div class="input-div">Search
<input type="text" id="txt_search">
</div>

<div class='tableOne'><br/>
<table>
<thead>
<th colspan="4" align="center">RESULTS</th>
<tr class="res"><td colspan="4" align="center">Matches:</td></tr>
<tr>
<th align="center">COL1</th>
<th align="center">COL2</th>
<th align="center">COL3</th>
<th align="center">COL4</th>
</tr>
</thead>

<!-- results -->
<div id="output">

</div>
<!-- results -->

</table>
</div>


Within the form I've added a
DIV
called output, I'm now trying to get my returned results to display in that.

When the search is done, the results returned are in the following format :

<tr>
<td>1a</td>
<td>1b</td>
<td>1c</td>
<td>1d</td>
</tr>

<tr>
<td>2a</td>
<td>2b</td>
<td>2c</td>
<td>2d</td>
</tr>


I'm using JQuery to populate the output DIV using :

$('#output').html(data)


This results in the returned data appearing above and outside of the table.

Yet if I create a if I manually add the same data to the table, the layout is fine.. as can be seen here : https://jsfiddle.net/Lz49fe6x/1/

What am I doing wrong ?
How do I get my returned results to appear correctly in the table ?

Thanks

Answer

div tag cannot be placed inside a table, you have to switch for tbody instead of div.

<div class="input-div">Search 
    <input type="text" id="txt_search">
</div>

<div class='tableOne'><br/>
<table>
    <thead>
    <th colspan="4" align="center">RESULTS</th>
    <tr class="res"><td colspan="4" align="center">Matches:</td></tr>
    <tr>
        <th align="center">COL1</th>
        <th align="center">COL2</th>
        <th align="center">COL3</th>
        <th align="center">COL4</th>
    </tr>
    </thead>

    <!-- results -->
    <tbody id="output">

    </tbody> 
    <!-- results -->

</table>
</div> 

Now append your rows in this tbody using following code.

$('#output').html(data)

View update fiddle at https://jsfiddle.net/Lz49fe6x/2/

Comments