I have a html table with following structure
<table class="mytable">
<tbody class="body">
<tr class="headline1"> ... several td tags with some text ... </tr>
<tr class="headline2"> ... several td tags with some text ... </tr>
<tr class="content"> ... several td tags with some text ... </tr>
<tr class="content"> ... several td tags with some text ... </tr>
<tr class="content"> ... several td tags with some text ... </tr>
<tr class="content"> ... several td tags with some text ... </tr>
<tr class="sum"> ... several td tags with some text ... </tr>
</tbody>
</table>
The structure of the table cannot be changed. Now I want to replace the lines (<tr>
elements) with class "content" and "sum" with the result of an ajax call (search.php generates the same table structure like described before)
My current code looks like:
$(document).ready(function(){
const search_field = $('#search_field');
search_field.keyup(function(){
$.ajax({
url:'http://someurl/search.php?search=' + search_field.val(),
type:"POST",
success:function(data){
var xxx = $(data).find('.body').html();
$('.body').html(xxx);
}
});
});
});
The code works but replaces the whole tbody. I would like to replace only the <tr>
elements (with all <td>
elements included in the <tr>
element). So the two headlines should be kept and not taken from the result of the ajax call.
An easy solution would be to close the <tbody>
element after the headlines and create a new <tbody>
element with a different id/class. But as already mentioned this is not possible because I cannot change the structure of the table
2
Answers
Or using a loop for .content rows:
.sum
row.content
rows.content
from the new data HTML.before()
method to insert the new rows before your.sum
element row.on()
method on your Search input. A use could as well paste a value into it, in which case the key events will not registerTip: nowadays, you don’t necessarily need jQuery:
Anyways, if possible, your
search.php
should be better rewritten to serve JSON data. Such data can be reused within many other components that do not necessarily use<table>
. Also, you don’t necessarily need to use such JSON data from the frontend, but also from other backend scripts. Think about it, a rewrite of your server-side API logic could be helpful on the long run.