Reputation: 1027
The HTML:
<table class="table table-bordered table-hover">
<thead>
<tr class="warning">
<th> Date </th>
<th> Teacher </th>
<th> Join conference </th>
</tr>
</thead>
<tbody id="lessons_tbody"></tbody>
</table>
Using Jquery 3.2.1, I have the following code:
$.each(ev, function(key,lesson) {
$('<tr class="active">').appendTo('#lessons_tbody');
$.each(lesson, function(key2, value){
if(key2=='url')
$('#lessons_tbody').append('<td><a href="'+value+'"><button class="btn btn-primary">Launch Lesson</button></a></td>');
else
$('#lessons_tbody').append('<td>'+value+'</td>');
});
$('</tr>').appendTo('#lessons_tbody');
});
This is the resulting HTML:
<tbody id="lessons_tbody">
<tr class="active"></tr>
<td>2020-06-23 12:00:00</td>
<td>Testi Test</td>
<td><a href="/conference/lesson/47/"><button class="btn btn-primary">Launch Lesson</button></a></td>
</tbody>
I need the td cells to be inside the table row elements (...)
EDIT 1 - Json response:
Upvotes: 1
Views: 199
Reputation: 28522
You can append
your html created in some variable using +=
and lastly append the same to your tbody
.
Demo Code :
//your response
var ev = [{
lessonDate: " 2020-08-12 12:40",
teacher: "abc",
url: "htp://ww.abc.com"
}, {
lessonDate: " 2020-09-12 10:40",
teacher: "abc1",
url: "htp://ww.abc1.com"
}, {
lessonDate: "2020-02-12 12:40",
teacher: "abc2",
url: "htp://ww.abc2.com"
}];
var html = "";
$.each(ev, function(key, lesson) {
//append tr in html variable
html += '<tr class="active">';
$.each(lesson, function(key2, value) {
if (key2 == 'url')
html += '<td><a href="' + value + '"><button class="btn btn-primary">Launch Lesson</button></a></td>';
else
html += '<td>' + value + '</td>';
});
html += '</tr>';
});
$("#lessons_tbody").append(html) //append row to tbody
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table class="table table-bordered table-hover">
<thead>
<tr class="warning">
<th> Date </th>
<th> Teacher </th>
<th> Join conference </th>
</tr>
</thead>
<tbody id="lessons_tbody"></tbody>
</table>
Upvotes: 3