Looking for a solution to achieve an HTML table that takes the "title" from the JSON file and puts it in the first column of a 2 column table and the second column has the "description".
The description has to be tier as bullet points as it is an array within an array in the JSON file. The current way it is working is that it is one big block of data in the second column which looks like a giant sentence. I've tried putting each bullet point into its separate key pair but it is not feasible as it is time-consuming. Is there an option for an if statement that iterates over the array within an array? Open for other script alternatives.
var data = [
{
"title": "title1",
"description":["description1","description2"]
},
{
"title": "title2",
"description":["description3","description4"]
}
]
$(document).ready(function(){
var list = '';
$.each(data, function(key, value){
list += '<tr>';
list += '<td>'+value.title+'</td>';
list += '<td>'+value.description+'</td>'
list += '</tr>';
});
$('#table1').append(list);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="table1">
<tr>
<th>Title</th>
<th>Description</th>
</tr>
</table>
Your current method is fine. You just need to add an $.each inside an $.each:
$(document).ready(function () {
$.getJSON("data.json", function (data) {
var list = '';
$.each(data, function (key, value) {
list += '<tr><td>' +
value.title +
'</td><td><ul>';
$.each(value.description, function (key, value) {
list += "<li>" + value + "</li>";
})
list += '</ul></td></tr>';
});
$('#table1').append(list);
});
});
var data = [{
"title": "title1",
"description": ["description1", "description2"]
},
{
"title": "title2",
"description": ["description3", "description4"]
}
]
$(document).ready(function() {
var list = '';
$.each(data, function(key, value) {
list += '<tr><td>' +
value.title +
'</td><td><ul>';
$.each(value.description, function(key, value) {
list += "<li>" + value + "</li>";
})
list += '</ul></td></tr>';
});
$('#table1').append(list);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="table1">
<tr>
<th>Title</th>
<th>Description</th>
</tr>
</table>
EDIT: Improved Version:
JSFiddle
Related
I need to implement a delete function for posts. I'm showing all the posts in a table. I can't seem to find a better way to show all the post.
This is the html:
<table border="1" id="show__posts" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>User Id</th>
<th>Post Id</th>
<th>Post</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JQuery code for loading posts
var loadposts=function(){
$.ajax({
url:"http://localhost:12091/api/post/",
crossdomain: true,
method:"GET",
complete:function(xmlhttp,status){
if(xmlhttp.status==200)
{
var data=xmlhttp.responseJSON;
$("#msg").html(data[0]);
console.log(data[0]);
var str='';
for (var i = 0; i < data.length; i++) {
str += "<tr>";
str += "<td>"+data[i].UserId+"</td>";
str += "<td>"+data[i].PostId+"</td>";
str += "<td>"+data[i].Post1+"</td>";
str += "<td><button
onclick='deletepost("+data[i].PostId+")'>Delete me</button></td>";
str += "</tr>";
}
$("#show__posts tbody").html(str);
}
else
{
$("#msg").html(xmlhttp.status+":"+xmlhttp.statusText);
}
}
});
}
loadposts();
Incomplete JQuery Code for Delete Post
var deletepost=function(){
$.ajax({
url:"http://localhost:12091/api/post/"+deleteid, <--how should I get this id from the table?
method: "DELETE",
header:"Content-Type:application/json",
data:post,
complete:function(xmlhttp, status){
if(xmlhttp.status == 204)
{
alert("Post Deleted");
}
else{
console.log(xmlhttp.status+":"+xmlhttp.statusText);
}
}
})
}
Finally my Code in controller
public IHttpActionResult Delete(int id)
{
postRepository.Delete(id);
return StatusCode(HttpStatusCode.NoContent);
}
Now my questions:
Is there a better way to show posts in webpage except table? I need to show user id, post id, post
how should I get the post ID from html and use it to delete the post?
**
Update:
I've completed the delete function like suggested:
var deletepost=function(deleteid){
$.ajax({
url:"http://localhost:12091/api/post/"+deleteid,
method: "DELETE",
header:"Content-Type:application/json",
data:deleteid,
complete:function(xmlhttp, status){
if(xmlhttp.status == 204)
{
alert("Post Deleted");
}
else{
console.log(xmlhttp.status+":"+xmlhttp.statusText);
}
}
})
}
The error that I'm getting:
Uncaught ReferenceError: deletepost is not defined
Tables are a long debate and depends on framework you are using. In bootstrap they use it : Bootstrap tables
You just need to add your id in you delete function :
var deletepost=function(deleteid){
...
}
Then add a column to your table for displaying a delete button :
for (var i = 0; i < data.length; i++) {
str += "<tr>";
str += "<td>"+data[i].UserId+"</td>";
str += "<td>"+data[i].PostId+"</td>";
str += "<td>"+data[i].Post1+"</td>";
str += "<td>";
str += "<button onclick='deletepost("+data[i].PostId+")'>Delete me</button>";
str += "</td>";
str += "</tr>";
}
You shouldn't use complete method but sucess and error. Complete is for executing code in both case.
$.ajax({
success: function (data) {
box.html(data);
},
error: function() {
box.html("Sorry.");
}
});
I wanted to clear all the search result shown by ajax search like when the user type for next query it will update it.
$(document).ready(function(){
var text;
$("#button").on('click',function (e) {
e.preventDefault();
var q=$("#q").val();
$.ajax({
url: "/search",
data: {q:q},
type: "GET",
dataType : "json",
success: function(result) {
var event_data = '';
for (var i = 0; i < result.length; i++) {
event_data += '<tr>';
event_data += '<td>' + '<img src=' +result[i]['video']['thumbnail_src']+ '></img>' +'</td>';
event_data += '<td>' +result[i]['video']['title']+'</td>';
event_data += '<td>' +result[i]['video']['duration']+ '</td>';
event_data += '<td>' + '<a href' +result[i]['video']['url']+ '>'+ "Download" +'</a>' +'</td>';
event_data += '</tr>';
} $("#list_table_json").append(event_data);
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
},
always: function( xhr, status ) {
alert( "The request is complete!" );
}
});
});
});
This is my html file for table where i was appending result from ajax success, can you guys let me know another technique for this. I wanted to clear previous result and update the new result.
Search
<table class="table table-responsive table-hover table-bordered" id="list_table_json">
<thead>
<tr>
<th>Thumbnail</th>
<th>Title</th>
<th>Duration</th>
<th>Download</th>
</tr>
</thead>
On the start of the success handler, use the below code if you want to keep the first tr (headings) and remove the rest of the data
$("#list_table_json").find("tr:gt(0)").remove();
or use if you want to remove everything
$("#list_table_json").empty();
or another way to remove everything
$("#list_table_json").html('');
How to use?
success: function(result) {
$("#list_table_json").find("tr:gt(0)").remove();
var event_data = '';
Question:
I need to create a table with a nested table format. When a user clicks plus button it should show the nested table. If they click minus button it should hide.
I have done jquery datatable its working fine. but I'm not able to display multiple rows for child table. I have tried so many times I'm not able to display proper format.
This is the link I have referred to create a table
https://datatables.net/examples/api/row_details.html
Database:
Actual data coming from the database as per the below format and I have converted JSON format to display :
C# Code:
return new JsonResult { Data = new { data = test }, JsonRequestBehavior =
JsonRequestBehavior.AllowGet };
I need an output like this with a nested table:
UI CODE:
/* Formatting function for row details - modify as you need */
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-
left:50px;">'+
'<tr>' +
'<td>City Name</td>' +
'<td>Permission</td>' +
'</tr><tr>' +
'<td>' + d.City+ '</td>' +
'<td>' + d.Permission+ '</td>' +
'</tr>' +
'</table>';
}
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "../ajax/data/objects.txt",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "UserName" },
{ "data": "Email" },
{ "data": "UserId" },
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
JSON FORMAT:
{"data":[
{"UserId":"ABC","UserName":"Peter","Email":"abc#gmail.com.com","CityName":"Chennai","Permission":"Manager,LocalUser"},
{"UserId":"ABC","UserName":"Peter","Email":"abc#gmail.com.com","CityName":"Bangalore","Permission":"Admin,LocalUser"},
{"UserId":"xyz","UserName":"Haiyan","Email":"abc2#gmail.com.com","CityName":"Bangalore","Permission":"LocalUser"},
{"UserId":"xyz","UserName":"Haiyan","Email":"abc2#gmail.com.com","CityName":"Chennai","Permission":"LocalUser,Manager"}]}
Technology used: ASP.Net MVC5
Any other way I'm ready to use either linq or modify JSON data format.
You can give Id to your child table like this
function format ( d ) {
// `d` is the original data object for the row
return '<table id="childtable" cellpadding="5" cellspacing="0" border="0" style="padding-
left:50px;">'+
'<tr>' +
'<td>City Name</td>' +
'<td>Permission</td>' +
'</tr><tr>' +
'<td>' + d.City+ '</td>' +
'<td>' + d.Permission+ '</td>' +
'</tr>' +
'</table>';
}
and do the same thing which you did for your parent table
var childTable = $('#childtable').DataTable( {
"ajax": "../ajax/data/objects.txt",
"columns": [
],
"order": [[1, 'asc']]
} );
bind your json object in columns section.
We would be grateful for some guidance, [we are early into coding] and have looked at lots of examples but can cannot get our JSON to import into the table.
At that moment we have the table data in-line however a correctly formatted JSON file is now available and automatically updates and we want to load it into the table on the fly when the page is loaded.
This is an example of what were currently use:
<div>
<p> *** OTHER STUFF HERE ***<p/>
<table id="gable">
<colgroup>
<col class="twenty" />
<col class="fourty" />
<col class="thirtyfive" />
<col class="twentyfive" />
</colgroup>
<tr>
<th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>  COUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>  LOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>  BALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>  DATE</th>
</tr>
</table>
</div>
<script>
var data = [
{ "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
{ "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
{ "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
{ "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
{ "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
];
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
'<td>' + object.LoC + '</td>' +
'<td>' + object.BALANCE + '</td>' +
'<td>' + object.DATE + '</td>';
table.appendChild(tr);
});
</script>
There are a lot more lines of data, the table has CSS styling and applies the sortTable(n) function to the Headers. It displays perfectly, looks and functions like we want,
We've Googled [lots] and tried various load / populate scripts and attempted to get the example on w3schools working - https://www.w3schools.com/js/js_json_html.asp - alas we're fairly new to this.
Our JSON file /assets/sample.JSON is correctly formatted and meets the requirements.
How do we do a simple import of the JSON to populate the table id="gable"?
Ok, so in this solution I am going to assume that your external json file is called 'example.json'
Your external file should look something like this
example.json:
[
{ "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
{ "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
{ "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
{ "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
{ "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
]
The html remains the same all the changes have been made in the script tags. I split the functionality into 2 new functions. The first function (get_json_data) gets the json data from the external json file. The second function (append_json) appends the data to the table.
I have put comments throughout the code to explain what everything is doing. if you have any questions or if something is unclear let me know.
here is the code for the html file:
<div>
<p> *** OTHER STUFF HERE ***<p/>
<table id="gable">
<colgroup>
<col class="twenty" />
<col class="fourty" />
<col class="thirtyfive" />
<col class="twentyfive" />
</colgroup>
<tr>
<th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>  COUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>  LOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>  BALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>  DATE</th>
</tr>
</table>
</div>
<script>
//first add an event listener for page load
document.addEventListener( "DOMContentLoaded", get_json_data, false ); // get_json_data is the function name that will fire on page load
//this function is in the event listener and will execute on page load
function get_json_data(){
// Relative URL of external json file
var json_url = 'example.json';
//Build the XMLHttpRequest (aka AJAX Request)
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {//when a good response is given do this
var data = JSON.parse(this.responseText); // convert the response to a json object
append_json(data);// pass the json object to the append_json function
}
}
//set the request destination and type
xmlhttp.open("POST", json_url, true);
//set required headers for the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// send the request
xmlhttp.send(); // when the request completes it will execute the code in onreadystatechange section
}
//this function appends the json data to the table 'gable'
function append_json(data){
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
'<td>' + object.LoC + '</td>' +
'<td>' + object.BALANCE + '</td>' +
'<td>' + object.DATE + '</td>';
table.appendChild(tr);
});
}
</script>
you can have a function to create the table independent from your data fields:
function updateTable(tableId, jsonData){
var tableHTML = "<tr>";
for (var headers in jsonData[0]) {
tableHTML += "<th>" + headers + "</th>";
}
tableHTML += "</tr>";
for (var eachItem in jsonData) {
tableHTML += "<tr>";
var dataObj = jsonData[eachItem];
for (var eachValue in dataObj){
tableHTML += "<td>" + dataObj[eachValue] + "</td>";
}
tableHTML += "</tr>";
}
document.getElementById(tableId).innerHTML = tableHTML;
}
I have a problem, I've created a simple webpart that perfoms basics CRUD OPERATIONS, I wanted to add an HTML table to format and display the results retrieved from the READ operation, here is the code for a better understanding:
function retriveListItem() {
execute(
"items?$orderby=Nom&$select=Nom,Cognom,Indirizz",
"GET",
"GET",
null,
function (data, status, xhr) {
$("#result").empty();
var string = "<table><tr><th>Nome</th><th>Cognome</th><th>Indirizzo</th></tr>";
$("#result").append(string);
string = string = "";
for (var i = 0; i < data.d.results.length; i++) {
var item = data.d.results[i];
string = "<tr><td>" + item.Nom + "</td><td>" + item.Cognom + "</td><td>" + item.Indirizz + "</td></tr>";
$("#result").append(string);
}
string = "</table>";
$("#result").append(string);
},
function (xhr, status, error) {
$("#result").empty().text(error);
});
}
But when the page is rendered in the browser if I hit the F12 key I discover that sharepoint automatically adds the tbody tag (which I haven't wrote) and it close the tag /table automatically in the wrong position here is the code rendered in the browser:
<div id="result">
<table>
<tbody>
<tr>
<th>Nome</th>
<th>Cognome</th>
<th>Indirizzo</th>
</tr>
</tbody>
</table>
<tr>
<td>Giova</td>
<td>Nardi</td>
<td>Viale della Cagna, Verona</td>
</tr>
<tr>
<td>Antonio</td>
<td>Petrarca</td>
<td>Via Camello 31, Rovegna</td>
</tr>
<tr>
<td>Luca</td>
<td>Mandelli</td>
<td>Via Rossini, 32 Cesano Maderno</td>
</tr>
</div>
Does anybody knows why that? Any idea on how to workaround that issue? Thanks a lot
It looks like in your code, your string variable is just overwriting itself, and you are posting the results to the browser each time. Rather than using .append() each time you update the string, just use a string += .... and then append after the loops have run and the string is populated with the full table.
Here is a JSFiddle as an example using your code (for the most part).
So your code would look like:
function retriveListItem() {
execute(
"items?$orderby=Nom&$select=Nom,Cognom,Indirizz",
"GET",
"GET",
null,
function (data, status, xhr) {
$("#result").empty();
var string = "<table><tr><th>Nome</th><th>Cognome</th><th>Indirizzo</th></tr>";
//$("#result").append(string);
//string = string = "";
for (var i = 0; i < data.d.results.length; i++) {
var item = data.d.results[i];
string += "<tr><td>" + item.Nom + "</td><td>" + item.Cognom + "</td><td>" + item.Indirizz + "</td></tr>";
//$("#result").append(string);
}
string += "</table>";
$("#result").append(string);
},
function (xhr, status, error) {
$("#result").empty().text(error);
});
}
Hope this helps!
You can always insert HTML into an existing table using JQuery's after() method. Since you have a first <tr> already, you can poke in your built up HTML after that first row:
// First, put your basic table into #result
$("#result").html('<table id="resulttable"><tr><td>...</td></tr></table>');
// Next build up the necessary rows and columns
for (var i = 0; i < data.d.results.length; i++) {
// Build up your string as above
}
// Next, poke it into the DOM after the first <tr>
$("#resulttable tr").first().after(string);
You will find a full mockup below. The results data and the code to populate rows is shown in the page's <head> section. Below that, in the <body> a table is defined with ID mytab. That ID is picked up in the code that populates the rows.
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
data = { d : {
results: [
{ Nom: 'nom1', Cognom: 'Cognom1', Indirizz: 'Indirrizz1' },
{ Nom: 'nom2', Cognom: 'Cognom2', Indirizz: 'Indirrizz2' },
{ Nom: 'nom3', Cognom: 'Cognom3', Indirizz: 'Indirrizz3' } ] } };
$(document).ready(function() {
for (var i = 0; i < data.d.results.length; i++) {
item = data.d.results[i]
str = '<tr><td>' + item.Nom + '</td><td> ' + item.Cognom +
'</td><td>' + item.Indirizz + '</td></tr>';
$('#mytab tr').first().after(str);
}
});
</script>
</head>
<body>
<table id="mytab">
<tr>
<td>First column</td> <td>Second column</td> <td>Third column</td>
</tr>
</table>
</body>
</html>