I am creating a table as below in my Javascript:
var l_table = op.script.table_dom_start + op.script.l_table_header + l_table_rows + op.script.table_dom_end;
Which results in:
<table class="table table-hover">
<tr>
<th class="capitalize">
...
</th>
</tr>
</table>
Which is then appended to target div:
$(l_table).appendTo('#l-ajax-response-div');
Now, before appending, I want to give this class an id and tried below ways:
$(l_table).attr('id', 'l-entry-table');
and
l_table.id='l-entry-table';
Both of these fail to work, what is going on here?
Variable contents:
table_dom_start: '<table class="table table-hover">',
header: specific header for that table
row: specific rows for that table
table_dom_end: '</table>',
Try something like this:
var mytable=$(l_table);
mytable[0].id="l-entry-table";
mytable.appendTo('#l-ajax-response-div');
Check this below example it will alert no of tables found by id.
var l_table = '<table class="table table-hover"><tr><th class="capitalize">Table with ID</th></tr></table>';
$(l_table).attr('id', 'l-entry-table').appendTo('#l-ajax-response-div');
alert($('#l-entry-table').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="l-ajax-response-div"></div>
Related
I am trying to display a table with a list of public holidays. At the moment I have a table row with the holiday name on the left and date on the right.
The data which appears is from the final array of the JSON object only where I want to display all of the public holidays.
html of table:
<table class="table table-striped" >
<tbody class="summT">
<div class="resptext">
<tr>
<td align="left" id="txtHolidayName">
</td>
<td class="fontGrey" id="txtHolidayDate">
</td>
</tr>
</div>
</div>
</tbody>
</table>
I have the following code within the success block of the AJAX call to the api:
.............
result.data.response.holidays.forEach(datepoint => {
$dateIterate = new Date(datepoint.date.iso);
$('#txtHolidayDate').html($dateIterate.toDateString());
$('#txtHolidayName').html(datepoint.name);
})
Any ideas are gratefully appreciated. Thank you so much.
I think what you are going to need to do is have template HTML within your loop that you populate with each iteration, and then inject each copy of the filled out template into the table HTML:
HTML:
<table class="table table-striped" >
<tbody class="summT">
<div id="holidates" class="resptext">
</div>
</tbody>
</table>
JavaScript loop:
result.data.response.holidays.forEach(datepoint => {
$('#holidates').append('<tr>\n' +
'<td align="left" >' + datepoint.name + '</td>' +
'<td class="fontGrey" >' + new Date(datepoint.date.iso).toDateString() + '</td>\n' +
'</tr>');
});
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);
For some reason the following piece of code does not work to insert an extra table into my html document. The text is just randomly sitting at the top of the table instead of IN the table. Any ideas why it doesn't work?
<!DOCTYPE html>
<head>
<script type = "text/javascript">
function insertTable() {
var table = document.getElementById("houseListingTable").innerHTML;
table = table + "<tr><td>58,500</td><td>Montreal</td></tr>";
}
</script>
</head>
<body>
<table>
<tr>
<th>Price</th>
<th>Location</th>
</tr>
<div id = "houseListingTable">
</div>
</table>
<button onclick = "insertTable()">Insert Table<\button>
</body>
</html>
Why doesn't the table row add itself to my table when I click on the Insert Table button? Any help is appreciated!!
There are two problems here:
Having a <div> element directly inside a <table> is invalid HTML.
Your table variable here is just a string. Overwriting it has no effect on the DOM.
To fix it:
Remove the <div> and give the <table> an ID:
<table id="houseListingTable">
<tr>
<th>Price<\th>
<th>Location<\th>
</tr>
</table>
Use this JavaScript:
var table = document.getElementById("houseListingTable");
table.innerHTML += "<tr><td>58,500</td><td>Montreal</td></tr>";
Note how I am actually overwriting the table's .innerHTML property. This is an important distinction from what you have there.
Just a couple of comments before the answer. Please note that you are missing the html tag at the begging, and that you are using the incorrect bar "\" to close tags in table headers (it should be < /th>) and in the button tag (< /button>).
Also, the div inside the table is not correct.
The code does nothing because the function just gets the innerHTML. For your purpose, the function should get what's inside the table, add a row and then paste it back on the table
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function insertTable() {
var table = document.getElementById("houseListingTable").innerHTML;
table = table + "<tr><td>58,500</td><td>Montreal</td></tr>";
document.getElementById("houseListingTable").innerHTML = table;
}
</script>
</head>
<body>
<table id="houseListingTable">
<tr>
<th>Price</th>
<th>Location</th>
</tr>
</table>
<button onclick = "insertTable()">Insert Table</button>
</body>
</html>
Your HTML is broken. The ending tags are wrong.
<table id="houseListingTable">
<tr>
<th>Price</th>
<th>Location</th>
</tr>
</table>
You can use the insertRow of DOM method to add rows to table by getting the table first by Id
function insertTable() {
// Find a <table> element with id="houseListingTable":
var table = document.getElementById("houseListingTable");
// Create an empty <tr> element and add it to the table:
var row = table.insertRow(table.rows.length);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// Append a text node to the cell1
var price = document.createTextNode('58,500')
cell1.appendChild(price);
// Append a text node to the cell2
var location = document.createTextNode('Montreal')
cell2.appendChild(location);
}
I have table that is built dynamically with Razor in MVC.
I want to be able to click on the a row and get the value of lets's say the first column ID.
Right now it's getting all the columns but I don't know too much Javascript or how it's stored with text.
Anyways what I'm looking for is to get a certain column on the row I clicked.
Razor MVC
<table id="myTable" class="tablesorter">
<thead>
<tr>
<th>ID</th>
<th>Owner</th>
</tr>
</thead>
<tbody>
#for(int i=0; i<Model.changes.Count(); i++)
{
<tr>
<td>#Model.changes[i].ID</td>
<td>#Model.changes[i].Owner</td>
</tr>
}
</tbody>
</table>
Javascript
<script>
var table = $("#myTable tr");
table.click(function () {
alert($(this).text());
});
</script>
You can use nth-child,
Live Demo
var table = $("#myTable tr");
table.click(function () {
alert($(':nth-child(1)', this).text());
});
I'm trying to start the table empty with no data in <tbody> and choose some parameters send to the server via $.getJSON and append the returned json data inside <tbody>.
But it looks like because of the $(document).ready() it makes it not work properly, the pagination and the search stop working completely.
BTW, I'm including all the needed files, I know that the error is because I'm populating the table after the page loads, I just would like to know if there is another approach to solve this problem.
Here is my code:
<script type="text/javascript" src="../js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#contacts').dataTable({
"sPaginationType" : "full_numbers"
});
$("#submit").click(function()
{
$.getJSON("/myurl",
function(data)
{
$("#table_body").empty();
$.each(data, function(i, item)
{
$("#table_body").show("slow");
$("#table_body")
.append(
'<tr class="gradeC">' +
'<td>' + item.name+ '</td>' +
'<td>' + item.birthdate + '</td>' +
'<td>' + item.age + '</td>' +
'</tr>'
);
});
});
});
});
</script>
<!-- NOW THE HTML CODE FOR THE TABLE -->
<table cellpadding="0" cellspacing="0" border="0" class="display" id="contacts">
<thead>
<tr>
<th>Name</th>
<th>Birthdate</th>
<th>Age</th>
</tr>
</thead>
<tbody id="table_body"></tbody>
<tfoot>
<tr>
<th>Name</th>
<th>Birthdate</th>
<th>Age</th>
</tr>
</tfoot>
</table>
It doesn't appear that you are using the Datatables API properly. Read through the documentation and try using the datatables methods for adding rows and emptying the table, etc.
Try using the $(function() { ... }); syntax instead. I recently had an issue where $(document).ready(function() { ... }); wasn't working. I tried the newer syntax and it fixed it...
Hope this helps.
fnAddData() should not be used for loading entire content row by row. To table content from JSON you can set this url in the sAjaxSource property and define mappings between JSON properties and columns. See examples on:
http://datatables.net/release-datatables/examples/ajax/objects.html
http://datatables.net/release-datatables/examples/ajax/deep.html
I believe that your approach works, but take a look on this pages too maybe it would be easier to load them this way.
Jovan