i have a table that display data whenever a user clicks the start event button,but i need to know how to append the records when the user clicks the start button again,the previous record gets overridden
here is my javascript code
function DisplayData(downTime) {
console.log(downTime);
var newContent = '';
$.each(downTime.data, function (i, item) {
newContent += Hesto.Html.StartTR(item.downTime);
newContent += Hesto.Html.CreateTD(item.CategoryName);
newContent += Hesto.Html.CreateTD(item.StartTime);
newContent += Hesto.Html.CreateTD(item.EndTime);
newContent += Hesto.Html.CreateTD(item.Comments);
newContent = Hesto.Html.EndTR(newContent);
});
$('#DowntimeList').html(newContent);
}
and here is my html code:
<table id="Downtimetable" class="hesto">
<thead>
<tr>
<th>End Of DownTime</th>
<th>Category Name</th>
<th>Start Time</th>
<th>End Time</th>
<th>Comments</th>
</tr>
</thead>
<tbody id="DowntimeList">
</tbody>
<tfoot>
</tfoot>
</table>
Use append() instead of overwriting the html():
$('#DowntimeList').append(newContent);
As you suggested in the title of your question, append() it.
$('#DowntimeList').html(newContent);
Should be
$('#DowntimeList').append(newContent);
Simply use,
document.getElementById('DowntimeList').InnerHtml = document.getElementById('DowntimeList').InnerHtml+newContent
Related
I looked at previous similar questions and only found one answer with the following code splitting the data into 2 tables:
// ==UserScript==
// #name TABLE SPLITTER
// #namespace http://www.w3schools.com/
// #description DESCRIPTION!!!
// #include http://www.w3schools.com/css/css_table.asp
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// #require https://raw.github.com/tomgrohl/jQuery-plugins/master/jcookie/script/jquery.jcookie.min.js
// #version 1
// ==/UserScript==
$(function(){
// YOUR JAVASCRIPT CODE HERE
// YOU HAVE JQUERY INCLUDED
setTimeout(function(){
var mainTable = $("table");
var splitBy = 3;
var rows = mainTable.find ( "tr" ).slice( splitBy );
var secondTable = $("<table id='secondTable' style='background:pink;'><tbody></tbody></table>").insertAfter("table");
secondTable.find("tbody").append(rows);
console.log(secondTable);
mainTable.find ( "tr" ).slice( splitBy ).remove();
}, 3000);
});
I am looking for something like this that will split the information to tables base on the amount of different options i have.
ultimately i would like something like:
Goal
Or even better remove the type from the output and have it show before each of the new tables like this: option 2
Not sure if that even possible and would love some help.
This is not the optimal solution, you can get the idea and improve it.
Read JS comments.
var dynamicData = $('#dynamicData'); // To identify the parent that we will append data to.
$(document).ready(function(){
$('.types').each(function(){ // loop on each type and check if that type not appended inside '#dynamicData' as 'h5', if no,t append it and append a table related to it
var name = $.trim($(this).text());
var check = $('h5#i_' + name , dynamicData).length;
if (check === 0){
$(dynamicData).append('<h5 id="i_' + name + '">' + name + '</h5>');
$(dynamicData).append('<table id="t_' + name + '" class="table table-hover table-striped table-bordered"></table>');
$('table#t_' + name).append('<thead>'+
'<tr>'+
'<th>Product</th>'+
'<th>Price</th>'+
'</tr>'+
'</thead>'+
'<tbody>'+
'</tbody>');
}
});
$('#allContent > tr').each(function(){ // loop on each row in '#allContent' and read '.types' class, then clone this row and remove the type then append it inside the target table using id
var name = $.trim($('.types',this).text());
$(this).clone().find('.types').remove().end().appendTo('table#t_' + name + ' > tbody');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<h4 class="text-center text-danger">Before:</h4>
<table class="table table-hover table-striped table-bordered">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Type</th>
</tr>
</thead>
<tbody id="allContent">
<tr>
<td>TV</td>
<td>250$</td>
<td class="types">Product</td>
</tr>
<tr>
<td>Channel</td>
<td>1$</td>
<td class="types">Service</td>
</tr>
<tr>
<td>Channel</td>
<td>1$</td>
<td class="types">Service</td>
</tr>
<tr>
<td>DVD</td>
<td>14$</td>
<td class="types">Product</td>
</tr>
<tr>
<td>Support</td>
<td>15$</td>
<td class="types">Team</td>
</tr>
</tbody>
</table>
<h4 class="text-center text-danger">After:</h4>
<div id="dynamicData"></div>
My first thought is make a unique list of the types. Then loop over that list, cloning the original table for each. Then loop through the cloned table and remove everything that you don't want there. Definitely not the most efficient, but it's simple and it works.
let types = [... new Set($('table.original tr td:last-of-type')
.get().map(type => type.textContent))];
//create a container for the cloned tables
$('table.original').after(`<h4>After:</h4><div class="cloned-tables"></div>`)
//loop over types, clone tables, modify accordingly
$.each(types, function(index, type) {
$(`<p class="type">${type}</p>${$('table.original')[0].outerHTML}`)
.appendTo('.cloned-tables')
.find('tr td:last-of-type').each(function() {
if (this.textContent !== type) { this.parentElement.remove(); }
this.remove();
});
});
//remove all type header cells
$(`.cloned-tables table th:last-of-type`).remove();
h4{color: red;}
.type{color: blue;}
<h4>Before:</h4>
<table class="original">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>TV</td>
<td>$250</td>
<td>Product</td>
</tr>
<tr>
<td>Channel</td>
<td>$1</td>
<td>Service</td>
</tr>
<tr>
<td>Channel</td>
<td>$1</td>
<td>Service</td>
</tr>
<tr>
<td>DVD</td>
<td>$14</td>
<td>Product</td>
</tr>
<tr>
<td>Support</td>
<td>$15</td>
<td>Team</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Another thought on using greasemonkey, make sure that the table exist and is populated before you try and do anything with it. Greasemonkey is in a different scope than the original code, so document.ready() is inaccurate. Sometimes things load very asychronously, which will make valid code seem broken. I tend to do something like this:
let loading = setInterval(function() {
if ($('table.original').length) {
clearInterval(loading);
//greasmonkey code here
}
}, 1000);
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.
Trying to store all the information that getting from JSONP in the table.
Have done the test with 'alert' to make sure that there are more info that only one line and can see that there are more info that one.
But when run it, in the table I can see title row and first row.
Can somebody correct my error?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
</script>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.example.com/v1/deal/hotel?apikey=xxx&format=JSONP",
dataType : "jsonp",
success : function(parsed_json) {
$.each(parsed_json.Result, function( index, value ) {
alert( index + ": " + value.StarRating + " , "+ value.Url);
});
var from = parsed_json['Result'][0]['StartDate'];
document.getElementById("from").innerHTML = from;
var from = parsed_json['Result'][0]['StartDate'];
document.getElementById("from").innerHTML = from;
var to = parsed_json['Result'][0]['EndDate'];
document.getElementById("to").innerHTML = to;
var nights = parsed_json['Result'][0]['NightDuration'];
document.getElementById("nights").innerHTML = nights;
var currency = parsed_json['Result'][0]['CurrencyCode'];
document.getElementById("currency").innerHTML = currency;
var price = parsed_json['Result'][0]['Price'];
document.getElementById("price").innerHTML = price;
var link = parsed_json['Result'][0]['Url'];
document.getElementById("link").innerHTML = link;
//how to represent enlaces
var city = parsed_json['Result'][0]['City'];
document.getElementById("city").innerHTML = city;
var country = parsed_json['Result'][0]['CountryCode'];
document.getElementById("country").innerHTML = country;
var stars = parsed_json['Result'][0]['StarRating'];
document.getElementById("stars").innerHTML = stars;
}
});
});
</script>
</head>
<body>
<table id="t">
<tr>
<th>Start date</th>
<th>End date</th>
<th>Nights</th>
<th>Currency</th>
<th>Price</th>
<th>Link</th>
<th>City</th>
<th>Country Code</th>
<th>Star Rating</th>
</tr>
<tr>
<td id="from"></td>
<td id="to"></td>
<td id="nights"></td>
<td id="currency"></td>
<td id="price"></td>
<td id="link"></td>
<td id="city"></td>
<td id="country"></td>
<td id="stars"></td>
</tr>
</table>
</body>
</html>
The result of the Ajax callback is:
callback({"Errors":[],"Result":[{"FoundDate":"2013-12-04T16:11:36-08:00","CurrencyCode":"USD","NightDuration":"2.0","EndDate":"12/08/2013","Headline":"Cairo 5 Star Hotel, $36/night","IsWeekendStay":"true","Price":"36.0","StartDate":"12/06/2013","Url":"http‍://www.example.com/hotel/...&startDate=12/06/2013&endDate=12/08/2013&bid=0&sid=0","City":"Cairo","CountryCode":"EG","NeighborhoodLatitude":"30.0152","NeighborhoodLongitude":"31.1756","Neighborhood":"Cairo West - Giza","StarRating":"5.0","StateCode":"EG"},{"FoundDate":"2013-12-04T14:51:44-08:00",
If you have more than one line in result, then you have to -
Loop through it in the callback. You are not looping through it now. You are looping only for alert.
Dynamically create a new row in table for each line. You can clone the exiting tr for this using jquery clone method. But replace the id with 'class`.
Add data to that row pertaining to the line by modifying innerHtml of each td in the newly created row.
Finally, Append the row to the table
HTML -
<table id="t">
<tr>
<th>Start date</th>
<th>End date</th>
<th>Nights</th>
<th>Currency</th>
<th>Price</th>
<th>Link</th>
<th>City</th>
<th>Country Code</th>
<th>Star Rating</th>
</tr>
<tr class="first">
<td class="from"></td>
<td class="to"></td>
<td class="nights"></td>
<td class="currency"></td>
<td class="price"></td>
<td class="link"></td>
<td class="city"></td>
<td class="country"></td>
<td class="stars"></td>
</tr>
</table>
Javascript -
success : function(parsed_json) {
$.each(parsed_json.Result, function( index, record ) {
$row = $('.first').clone();
var from = record['StartDate'];
$row.find('.from').html(from);
//Similarly repeat the above two lines for other columns
//...
$('#t').append($row);
});
}
I have a simple HTML table like this:
<table>
<thead>
<tr>
<th id="lname"><span title="sort this column">Last Name</span>
</th>
<th id="fname"><span title="sort this column">First Name</span>
</th>
<th id="scanned"><span title="sort this column">Scanned In</span>
</th>
<th id="department"><span title="sort this column">Department</span>
</th>
<th id="category"><span title="sort this column">Category</span>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="blah">LNAME1</td>
<td>FNAME1</td>
<td>06/25/13 12:48 PM</td>
<td>Internal Medicine</td>
<td>Fellow</td>
</tr>
<tr>
<td class="blah">LNAME1</td>
<td>FNAME1</td>
<td>06/25/13 12:48 PM</td>
<td>Internal Medicine</td>
<td>Fellow</td>
</tr>
<tr>
<td class="blah">LNAME1</td>
<td>FNAME1</td>
<td>06/26/13 07:29 AM</td>
<td>Internal Medicine</td>
<td>Faculty</td>
</tr>
<tr>
<td class="blah">LNAME1</td>
<td>FNAME1</td>
<td>06/26/13 07:21 AM</td>
<td>Internal Medicine</td>
<td>Faculty</td>
</tr>
</tbody>
</table>
And a javascript/jquery code going something like this:
var count = 0;
var scannedArr = new Array();
$('table tr').each(function(){
var times = $(this).find('.blah').text();
scannedArr[count] = times;
count++;
});
What I'm trying to do in this javascript function is include the scannedArr array's elements all in a single alert(). Can I do that? Is there a simpler way to go about it?
Thanks in advance!
Try this
alert(scannedArr.join(''));
You can use join() to create single string of your array:
// using comma as a separtor
// you can pass any separator as: join('separator')
var everything = scannedArr.join();
alert(everything);
I would do this:
var tableStuff = $('table tr').map(function(){
return $(this).find('.blah').text();
}).get();
alert(tableStuff);
Now tableStuff is a nice array of the text from .blah
I tend to use:
alert(JSON.stringify(scannedArr));
You can use something like:
function printObject(o) {
var out = '';
for (var p in o) {
out += p + ': ' + o[p] + '\n';
}
alert(out);
}
But, i like more use console.log(array), with chrome (and you can see in the js console!)
var count = 0;
var scannedArr = new Array[];
$('table tr').each(function(){
var times = $(this).find('.blah').text();
scannedArr.push(times)
count++;
});
alert(scannedArr);
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.