I am using jQuery and I have script as below;
$(document).ready( function() {
$('.nm').each(function(row) {
$.ajax({
type: 'POST',
url: 'test.php',
data: 'id=' + 1,
dataType: 'json',
cache: false,
success: function(result) {
$('.title').each(function(index){
if (result) {
$(this).html(result[index]);
} else {
$(this).html(" ");
}
});
},
});
});
});
The script is suppose to change text in my table;
<tr class="nm" style="height: 30px">
<td style="width: 15px;"> </td>
<td class="section" colspan="5">Mix</td>
<td style="width: 15px;"> </td>
</tr>
<tr>
<td id="prev" rowspan="2"><<</td>
<td class="content"> </td>
<td class="content"> </td>
<td class="content"> </td>
<td class="content"> </td>
<td class="content"> </td>
<td id="next" rowspan="2">>></td>
</tr>
<tr>
<td class="title" > </td>
<td class="title" > </td>
<td class="title" > </td>
<td class="title" > </td>
<td class="title" > </td>
</tr>
<tr class="nm" style="height: 30px">
<td style="width: 15px;"> </td>
<td class="section" colspan="5">Mix</td>
<td style="width: 15px;"> </td>
</tr>
<tr>
<td id="prev" rowspan="2"><<</td>
<td class="content"> </td>
<td class="content"> </td>
<td class="content"> </td>
<td class="content"> </td>
<td class="content"> </td>
<td id="next" rowspan="2">>></td>
</tr>
<tr>
<td class="title" > </td>
<td class="title" > </td>
<td class="title" > </td>
<td class="title" > </td>
<td class="title" > </td>
</tr>
As you can see, the table has 6 rows, and it is in a 3 – row repeating format. The contents are filled by a test.php file which echos a JSON encoded array containing 5 members. In this way, all 5 cells having class="title" get populated successfully. But the second set with class="title" is not getting filled.
I made a each(function(row) to repeat the ajax call for every row having class="nm". But this is not working. I think the [index] is not getting reset after ajax, because the remaining cells are populating if I provide more than 5 members in array. But I want the ajax request to repeat after every row having class="nm" and want to fill the data accordingly.
How can I do this?
$('.title')always selects every.titleelement. You are not restricting the set to any particular one. You have to make the selector dependent on.nmsomehow.For example:
This should work with the structure you provided.
$rowreferences each<tr class="nm">row and$row.next().next()will select second next sibling, which is the row that contains the.titleelements.It will break if you change the structure.
It would be better if you give the rows containing the
.titleelements their own class:Then you can iterate of those instead of the
.nmrows, and get the.titleelements with$row.children('.title').