Insert an HTML table into sharepoint 2013 webpart script - html

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>

Related

How to delete post from table row using ajax for asp.net mvc?

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.");
}
});

JSON array into HTML table

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

How to find the index of the maximum value in html table and use it to find other information in the same row but another column?

In an HTML table, I have to obtain the maximum value of a column, then its position to find other information in another columns in the same row. Currently, I can find the maximum value but not its position in the column.
I have a classic table ans code like below:
<body>
<table id="tableau">
<thead>
<tr>
<th>#</th>
<th>Firstname</th>
<th>Lastname</th>
<th>City</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>José</td>
<td>Maire</td>
<td>Paris</td>
<td>1000</td>
</tr>
<tr>
<td>2</td>
<td>Lilianne</td>
<td>Maire</td>
<td>Paris</td>
<td>1234</td>
</tr>
<tr>
<td>3</td>
<td>Raymond</td>
<td>Fourbe</td>
<td>Bruxelles</td>
<td>123</td>
</tr>
<tr>
<td>4</td>
<td>Huguette</td>
<td>Fourbe</td>
<td>Bruxelles</td>
<td>129099</td>
</tr>
</tbody>
</table>
<button type="buttonmax" id="Score maximum" class="btn btn-info">Afficher le Score maximum</button>
<script>
var myArray = new Array();
$(document).ready(function()
{
$("#tableau tr td:nth-child(5)").each(function(i){
myArray.push($(this).text());
});
document.getElementById("Score maximum").onclick = function(){
var max = Math.max.apply(Math, $('td:nth-child(5)').map(function(i,elem){
return Number($(elem).text());
}));
alert(max);}
});
</script>
</body>
In my opinion, I have to find the index of the maximum value to display the the Firstname and Lastname of the person who realized this value, situated in the same row but in other columns.
Do you think it's the best way to do this?
I tried diverse codes to obtain the index of max but none worked.
Could you please help me to obtain the index and find the person who realized the best score?
This would be a way to achieve this (altough it is not very performant because it would overwrite the whole object if the current checked value is higher than the previous one).
PLEASE NOTE: I changed your id to "scoremaximum" because you really shouldn't have whitespaces in your id selector.
var max = {
score: 0,
id: 0,
firstname: '',
lastname: '',
city: ''
};
$("#tableau tr td:nth-child(5)").each(function(index, elem) {
var current = parseFloat($(elem).text());
if(current > max.score) {
max.score = current;
max.id = $("#tableau tr td:nth-child(1)")[index].textContent;
max.firstname = $("#tableau tr td:nth-child(2)")[index].textContent;
max.lastname = $("#tableau tr td:nth-child(3)")[index].textContent;
max.city = $("#tableau tr td:nth-child(4)")[index].textContent;
}
});
$('#scoremaximum').on('click', function() {
alert("score: " + max.score + ", id: " + max.id + ", firstname: " + max.firstname + ", lastname " + max.lastname + ", city: " + max.city);
});
You could increase the performance a little bit if you would add another property to the object that keeps track of the index outside of the loop and update it accordingly to the max.score. Then you could run a callback function after the loop has finished and pass it the max.index. That would look like this:
var max = {
score: 0,
index: 0,
id: 0,
firstname: '',
lastname: '',
city: ''
};
$("#tableau tr td:nth-child(5)").each(function(index, elem) {
var current = parseFloat($(elem).text());
if(current > max.score) {
max.score = current;
max.index = index;
}
return callback(max.index);
});
function callback(index) {
max.id = $("#tableau tr td:nth-child(1)")[index].textContent;
max.firstname = $("#tableau tr td:nth-child(2)")[index].textContent;
max.lastname = $("#tableau tr td:nth-child(3)")[index].textContent;
max.city = $("#tableau tr td:nth-child(4)")[index].textContent;
}
$('#scoremaximum').on('click', function() {
alert("score: " + max.score + ", id: " + max.id + ", firstname: " + max.firstname + ", lastname " + max.lastname + ", city: " + max.city);
});
Codepen: https://codepen.io/anon/pen/KYyyKV

Populate HTML table with JSON data

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>&nbsp&nbspCOUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</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>&nbsp&nbspCOUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</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;
}

Select all but one column of HTML table

I'm using the following to select a table element in my application for users to drag/drop a table into Excel:
$('#footer').on("click", "#exportSel", function () {
var el = document.getElementById(curTable);
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
var sel = window.getSelection ? window.getSelection() : document.selection;
if (sel) {
if (sel.removeAllRanges) {
sel.removeAllRanges();
} else if (sel.empty) {
sel.empty();
}
}
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
}
});
...and everything is working fine. Except one of my tables has images in a column, and I would like remove this column (or td's in that column) from the selection.
I added the "Picture" td's to a "nosel" class, and was able to put all td's in the table not in that class into a variable:
cells = $("#" + curTable + " tr td:not(.nosel)");
I then omitted the code to remove or empty the current selection, and tried adding each cell to the selection:
range.selectNode(cells[i]);
sel.addRange(range);
... but only the first td is being selected.
So two questions:
Is this even possible?
Is there a better method to use than addRange? I tried extend but that did not work.
As requested, here is an example of my table:
<table class="sortable" id="resultsTable" border="1">
<thead id="resultsHeader">
<th>OID</th>
<th>Image</th>
<th>Address</th>
<th>Parcel ID</th>
</thead>
<tbody id="resultsBody" data-ssimplename="results">
<tr>
<td>1</td>
<td align="center" class="nosel"><img style="width: 125px;" src="http://www.vanderburghassessor.org/assessor_images/12/180/34/213/020/12-180-34-213-020-S.jpg"></td>
<td align="center">5830 N KERTH AVE</td>
<td align="center">82-06-04-034-213.020-020</td>
</tr>
</tbody>
</table>
You can use the .not() function from jQuery.
$('myElements').not('myExcludedElements');
UPDATE:
JSFiddle would not load up for me for some reason so here it is in CodePen instead.
Example
I have decided to go about this another way.
Instead of removing the Image column from the selection, I am going to convert the images to the URL string when they make the selection:
`
for (i = 0; i < imgs.length; i++) {
var urlT = $(imgs[i]).attr('src');
$(imgs[i]).hide();
$(imgs[i]).parent().text(urlT);
}
`
This way the URL still exists to the image if in fact someone wants it.
The only issue is trying to restore the image once the selection is cleared. I tried adding an .on() function but it doesn't want to work correctly:
`
$('body').on('click', function () {
if ($("#" + curTable + " img:hidden").length > 0) {
var imgs = $('#' + curTable + " img:hidden");
for (i = 0; i < imgs.length; i++) {
$(imgs[i]).parent().text() = '';
imgs[i].show();
}
}
});
`
I can deal with it not restoring, but obviously I would prefer if it did.