tbody cant work in jquery - javascript

Why my tbody is not doing what I want, anyone can help me ?
This is my problem, in case I want to display in row but why that value just stay in column 1.2:
This is my jQuery:
$(function(){
$.ajax({
type: 'GET',
url: 'https://swapi.co/api/people/',
success: function(response) {
console.log(response);
var counter = 0;
var obj = response.results;
var Content = ' ';
var x = 0;
Content += '<tbody>'; //opening tag tbody
for(var i=0;i<obj.length; i++)
{
Content += '<tr>';
Content += '<td>'+obj[i].name+'</td>';
Content += '<td>'+obj[i].height+'</td>';
Content += '<td>'+obj[i].hair_color+'</td>';
Content += '<td>'+obj[i].skin_color+'</td>';
Content += '<td>'+obj[i].eye_color+'</td>';
Content += '<td>'+obj[i].birth_year+'</td>';
Content += '<td>'+obj[i].gender+'</td>'
Content += '</tr>';
}
Content += '</tbody>';
$('#results').empty();
$('#results').append(Content);
}
});
});
var tbody=document.getElementById("results");
var table=document.getElementById("tableId");
var tbodyIndex= [].slice.call(table.tBodies).indexOf(tbody);
And this my html
<table class="table table-stripted table-bordered table-hover" id="tableId">
<thead>
<tr>
<th>Name</th>
<th>Height</th>
<th>Hair Color</th>
<th>Skin Color</th>
<th>Eye Color</th>
<th>Birth Year</th>
<th>Gender</th>
</tr>
</thead>
<tbody id="results">
</tbody>
</table>
please help me , im newbie in javascript, oh yeah sorry for bad grammer, hope u guys help me , thank you

You don't have to add a tbody tag when your ajax response come in.
It's already in the DOM.
You can remove:
Content += '<tbody>';
Content += '</tbody>';

The HTML generated by your code is below.
Notice the two nested <tbody> elements, which disrupts the layout of your table.
GENERATED HTML
<table class="table table-stripted table-bordered table-hover " id="tableId">
<thead>
<tr>
<th>Name</th>
<th>Height</th>
<th>Hair Color</th>
<th>Skin Color</th>
<th>Eye Color</th>
<th>Birth Year</th>
<th>Gender</th>
</tr>
</thead>
<tbody id="results">
<tbody>
<tr>
<td>Luke Skywalker</td>
<td>172</td>
<td>blond</td>
<td>fair</td>
<td>blue</td>
<td>19BBY</td>
<td>male</td>
</tr>
</tbody>
</tbody>
</table>
As Maarten van Tjonger has already answered, remove <tbody> from your Content string to avoid its duplication.
Rather than using empty() and append(), I've used html() to replace the contents of the <tbody> with the new HTML.
Also, you'll want to execute dataTable() on the <table> itself, not the <tbody>.
WORKING EXAMPLE
$(function() {
$.ajax({
type: 'GET',
url: 'https://swapi.co/api/people/',
success: function(response) {
var obj = response.results,
Content;
for (var i = 0; i < obj.length; i++) {
Content += '<tr>';
Content += '<td>' + obj[i].name + '</td>';
Content += '<td>' + obj[i].height + '</td>';
Content += '<td>' + obj[i].hair_color + '</td>';
Content += '<td>' + obj[i].skin_color + '</td>';
Content += '<td>' + obj[i].eye_color + '</td>';
Content += '<td>' + obj[i].birth_year + '</td>';
Content += '<td>' + obj[i].gender + '</td>'
Content += '</tr>';
}
$('#results').html(Content);
$('#tableId').dataTable();
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<table class="table table-stripted table-bordered table-hover " id="tableId">
<thead>
<tr>
<th>Name</th>
<th>Height</th>
<th>Hair Color</th>
<th>Skin Color</th>
<th>Eye Color</th>
<th>Birth Year</th>
<th>Gender</th>
</tr>
</thead>
<tbody id="results">
</tbody>
</table>

You are missing the quotes around your tbody id <tbody id=results> should be <tbody id="results"> and you are generating a second <tbody> in your JS which is not necessary. Otherwise your code runs fine so see this fiddle with the problems corrected.

Related

Wanted to display all the row data inside the table BY ID

I wanted to fetch multiple row data in a table by ID but this code throwing all rows. IDK how to do that please review my code and give feedback. And also I attached the output image which I'm getting. I want to display all the row data inside the table where is (शिर्षक डेबिट क्रेडिट) these topics. [1]: https://i.stack.imgur.com/cFo7b.png
----modal-----
<script>
$(document).ready(function() {
$('.view_btn').click(function(e) {
e.preventDefault();
var id = $(this).closest('tr').find('.id').text();
$.ajax({
type: "GET",
url: " {{ route('biniyojan_popup_details') }}",
data: {
'checking_viewbtn': true,
'id': id,
},
//success: function(response){
success: function(data) {
var html = '';
var biniyojan_popup_details = data.biniyojan_popup_details;
if (biniyojan_popup_details.length > 0) {
for (let i = 0; i < biniyojan_popup_details.length; i++) {
html += `
<table border="1" class="table table-hover table-wrapper-scroll-y my-custom-scrollbar">
<thead class="text-white bg-primary" style="font-size: 14px;">
<tr>
<th scope="col">S.N </th>
<th scope="col">मिति </th>
<th scope="col">आ.ब </th>
<th scope="col">स्रोत व्यहोर्ने संस्था</th>
</thead>
<tbody class="bbody" style="font-size: 14px;">
<tr>
<td>` + biniyojan_popup_details\[i\]\['biniyojan_id'\] + `</td>
<td>` + biniyojan_popup_details\[i\]\['date'\] + `</td>
<td>` + biniyojan_popup_details\[i\]\['ab'\] + `</td>
<td>` + biniyojan_popup_details\[i\]\['school'\] + `</td>
</tr>
</tbody>
</table>
<table id="example" border="1" style=" width:50% ; " class="table table-hover table-wrapper-scroll-y my-custom-scrollbar">
<thead class="text-white bg-primary" style="font-size: 14px;">
<tr>
<th>शिर्षक</th>
<th>डेबिट</th>
<th>क्रेडिट</th>
</tr>
</thead>
<tbody class="text-dark" style="font-size: 14px;">
<tr>
<td>` + biniyojan_popup_details\[i\]\['kriyakalap'\] + `</td>
<td id="bujet">` + biniyojan_popup_details\[i\]\['cash'\] + `</td>
</tr>
<tr>
<td>` + biniyojan_popup_details\[i\]\['debit_credit_type'\] + `</td>
<td></td>
<td id="">` + biniyojan_popup_details\[i\]\['cash'\] + `</td>
</tr>
<tr class="text-white bg-secondary" style="font-size: 14px;">
<td style="font-weight:bold;">Total</td>
<td style="font-weight:bold;">` + biniyojan_popup_details\[i\]\['cash'\] + `</td>
<td style="font-weight:bold;">` + biniyojan_popup_details\[i\]\['cash'\] + `</td>
</tr>
</tbody>
</table>
`;
}
} else {
html += `
<tr>
<td colspan = "9" > Data not Found! </td>
</tr>
`;
}
$(".modal-body").html(html);
$('#exampleModalCenter').modal('show');
}
})
});
});
</script>
<!-- Modal Data -->][1]
----Controller-----
public function biniyojan_popup_details()
{
$biniyojan_popup_details = DB::table('biniyojan_details')
->leftJoin('biniyojan','biniyojan.biniyojan_id','biniyojan_details.biniyojan_id')
->get();
return response()->json(\['biniyojan_popup_details' => $biniyojan_popup_details\]);
}
Try this slight change. It adds a '=' to define what type of comparison we're making with biniyojan.biniyojan_id and biniyojan_details.biniyojan_id.
{
$biniyojan_popup_details = DB::table('biniyojan_details')
->leftJoin('biniyojan','biniyojan_details.biniyojan_id','=','biniyojan.biniyojan_id')
->get();
return response()->json(\['biniyojan_popup_details' => $biniyojan_popup_details\]);
}
You can try adding a where clause to your original code or try an alternative method using Models. This code works perfectly for me in my own project and I adapted it to your table names. I think you're trying to get details by an ID.
$biniyojan_popup_details = Biniyojan::where('biniyojan.biniyojan_id','=',$id)
->leftJoin('biniyojan_details','biniyojan.biniyojan_id','=','biniyojan_details.biniyojan_id')
->select('binoyojan_details.*','biniyojan.field1')
->get();

How to fetch JSOn response into HTML table using pure JS?

This is HTML markup:
<table id="prodTable" class="table table-bordered" style="color:white">
<thead class="thead">
<tr class="font-weight-bold">
<th>No.</th>
<th>Name</th>
<th>Category</th>
<th>Slug</th>
<th>Price</th>
<th>GST Price</th>
<th>Keywords</th>
<th>Specification</th>
<th>Description</th>
<th>Attributes</th>
<th>Available Stock</th>
<th>Payment Method</th>
<th>Approval Status</th>
<th>Approve</th>
<th>Deal of the Day</th>
<th>Edit & Delete</th>
</tr>
</thead>
<tbody class="tbody">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><lable><input type="checkbox" id="approveProd" name="approval" value="approval">Approve</label></td>
<td><label><input type="checkbox" id="DealoftheDay" name="dealoftheday" value="dealoftheday">Deal of the Day</label></td>
<td><button class="btn btn-outline-info" type="button"><i class="fa fa-pencil-square"></i></button> <button class="btn btn-outline-danger" type="button"><i class="fa fa-trash"></i></button></td>
</tr>
</tbody>
</table>
and my js is
function getProductsData() {
var data = "";
var type = "application/x-www-form-urlencoded";
var url = "get_product_data";
var asyn = "true";
var method = "POST";
var respCallback = function(resp){
var proddata = JSON.parse(resp);
var table = document.getElementById('prodTable');
console.log(table);
for (var i = 0; i < proddata.length; i++) {
console.log(proddata[i]);
};
}
var res=serverRequest(data,method,url,asyn,type,respCallback);
}
the getProductsData() is a onload function written in the body and am getting the response as JSON.
I need to know how to populate the JSON response into the table. Am new to js and i dont need jquery code. Because am learning js.
Thanks in advance.
Here is the short example which will help you, how to append the json data in HTML Table.
Example :-
function append_json_data(data){
var table = document.getElementById('prodTable');
data.forEach((object) => {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.No + '</td>' +
'<td>' + object.Name + '</td>' +
'<td>' + object.Category + '</td>' +
'<td>' + object.Slug + '</td>';
'<td>' + object.GST_Price + '</td>';
table.appendChild(tr);
});
}
And further you can apply the td tag for other elements as well, As I am showing you how to append the data to HTML you can add the tag data after 'GST_Price' same as above.

Delete contents of table and replace using JavaScript

I am trying to delete the contents of a upon click and repopulate it based on what they are clicking.
I was able to succesfully modify the with the new title, but I keep running into issues when I want to delete the contents of and replace it with a new one. I've tried doing the removeChild(), the replaceChild(), as well as innerHTML (which doesn't work based on documentation).
How would I successfully on a click, remove the existing table and repopulate it with HTML generated from JavaScript.
HTML:
<table id="captable" border = "5" width="100%" cellpadding="4" cellspacing="5">
<thead>
<tr>
<th colspan="100%">
<div id="table-title"></div>
</th>
</tr>
<th>Input Date</th>
<th>Requested Date</th>
</thead>
<tbody id="tbodyid">
<div id="table-entries">
<tr align = "center">
<td>3/27/2018</td>
<td>6/12/2018</td>
</tr>
</div>
</tbody>
</table>
JavaScript:
function(evt) {
$("#table-title").html("<h2><b>" + Title + ":</b><i> " + Subtitle + "</i></h2>");
var tBodyInner;
for (i of dataPoints) {
console.log("data" + i);
var data = json.Data[i];
tBodyInner += ("<tr align = \"center\">");
tBodyInner += ("<td><a target=\"_blank\" href=" + data.cap_url + ">" + data.capNumber + "</a></td>");
tBodyInner += ("</tr>");
}
//Not sure what to do here so that I clear the existing table, and appened the new tBodyInner html as a replacement
modal.style.display = "block";
}
First of all, you have to get rid of <div id="table-entries">, this is not a valid location for a DIV.
Second, you need to initialize the variable tBodyInner to an empty string.
Finally, you can use $("#tbodyId").html() to fill in the HTML of the table body.
function(evt) {
$("#table-title").html("<h2><b>" + Title + ":</b><i> " + Subtitle + "</i></h2>");
var tBodyInner = "";
for (i of dataPoints) {
console.log("data" + i);
var data = json.Data[i];
tBodyInner += ("<tr align = \"center\">");
tBodyInner += ("<td><a target=\"_blank\" href=" + data.cap_url + ">" + data.capNumber + "</a></td>");
tBodyInner += ("</tr>");
}
$("#tBodyId").html(tBodyInner);
modal.style.display = "block";
}
<table id="captable" border="5" width="100%" cellpadding="4" cellspacing="5">
<thead>
<tr>
<th colspan="100%">
<div id="table-title"></div>
</th>
</tr>
<th>Input Date</th>
<th>Requested Date</th>
</thead>
<tbody id="tbodyid">
<tr align="center">
<td>3/27/2018</td>
<td>6/12/2018</td>
</tr>
</tbody>
</table>
Where do you exactly change the html inside the element? You are setting the variable tBodyInner, but never using it. You should use it like you updated the title above, for example:
$("#table-entries").html(tBodyInner);
Also the parentheses around the string concats on the right side are redundant. No harm, but no effect either.

Adding <tr> <td> within a div with Javascript not showing within the table

I have a HTML table as below :
<table>
<tr>
<th>Name</th>
<th>Class</th>
<th>Reg ID</th>
</tr>
<tr>
<td>Alex</td>
<td>VII</td>
<td>56733</td>
</tr>
<div id="addfield"></div>
</table>
<input type="button" value="add" id="add_more_fields" />
And the jquery :
$(document).ready(function(){
var html = '';
$('#add_more_fields').click(function(){
html += '<tr>';
html += '<td>Steve</td>';
html += '<td>X</td>';
html += '<td>87777</td>';
html += '</tr>';
$('#addfield').append(html);
});
});
I wanted to add the <tr> generated by the javascript to be within the table. but when I clicked the button, the output is shown outside the table ! How can I display it within the
table ?
DEMO Here
It is not working because div inside table is invalid HTML structure. Append row to the table itself.
Also, you are not clearing the string html. Which causes multiple rows.
$('#add_more_fields').click(function () {
var html = ''; //declare string inside function
html += '<tr>';
html += '<td>Steve</td>';
html += '<td>X</td>';
html += '<td>87777</td>';
html += '</tr>';
$('table').append(html);
});
Updated fiddle here.
Try tbody inplace of #addfield like,
<table>
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>Reg ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alex</td>
<td>VII</td>
<td>56733</td>
</tr>
</tbody>
</table>
SCRIPT
$('#add_more_fields').click(function(){
html += '<tr>';
html += '<td>Steve</td>';
html += '<td>X</td>';
html += '<td>87777</td>';
html += '</tr>';
$('tbody').append(html);
});
Demo
Append Inside table
$('#add_more_fields').on('click',function(){
html += '<tr>';
html += '<td>Steve</td>';
html += '<td>X</td>';
html += '<td>87777</td>';
html += '</tr>';
$('table').append(html);//If you have more table then use id for table to append
});
You can't have a div inside a table. All you've gotta do is put the id on the table and remove the div.
<table id='addfield'>

looping through json data in JavaScript

This is similar to this question, but I thought I'd reword it a bit differently in order to make myself more clear.
I have this json coming back from a $.ajax call:
{"COLUMNS":["PERSONID","FIRSTNAME","LASTNAME"],"DATA":[[1001,"Scott","Wimmer"],[1002,"Phillip","Senn"],[1003,"Paul","Nielsen"]]}
Q: In JavaScript, how do I parse through it to make a table such as:
<table>
<thead>
<tr>
<th>PersonID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1001</td>
<td>Scott</td>
<td>Wimmer</td>
</tr>
<tr>
<td>1002</td>
<td>Phillip</td>
<td>Senn</td>
</tr>
<tr>
<td>1003</td>
<td>Paul</td>
<td>Nielsen</td>
</tr>
</tbody>
</table>
var yourJson = {"COLUMNS":["PERSONID","FIRSTNAME","LASTNAME"],"DATA":[[1001,"Scott","Wimmer"],[1002,"Phillip","Senn"],[1003,"Paul","Nielsen"]];
var table = '<table>';
table += '<thead><tr><th>' + yourJson.COLUMNS.join('</th><th>') + '</th></tr></thead>';
table += '<tbody>';
for (var i=0;i<yourJson.DATA.length;i++) {
table += '<tr><td>' + yourJson.DATA[i].join('</td><td>') + '</td></tr>';
};
table += '</tbody>';
table += '</table>';
You can use client side templating engine such as jTemplates or pure to achieve it easily.

Categories