Load the data into html table from json formatted variable - javascript

I need to load json dump data returning from a python script into my html table, not sure what am i doing wrong as i am relative new to html and doing this for a POC. I'm unable to load the data into a html table. seeking your help.
Python Code
def read_data_from_sql(sqlserverinst,uname,psswd,dbname,url,regime,jurisdiction):
output=[]
conn = pymssql.connect(sqlserverinst, uname, psswd, dbname)
cursor = conn.cursor(as_dict=True)
cursor.execute('SELECT * FROM [reg_content_extracted_url_browsed]')
for row in cursor:
output.append({'url_id': row['url_id'],'url': row['url'],'regime': row['regime'],'jurisdiction': row['jurisdiction']})
# flat_list = [item for sublist in output for item in sublist]
conn.close()
print(json.dumps(output))
return json.dumps(output)
Output format : [{"url_id": 1, "url": "www.google.com", "regime": "FATCA", "jurisdiction": "SG"}]
HTML Table layout
<div class="content-large">Successful Browsed URL(s)
<!-- <style>
table, th, td {
border:1px solid black;
}
</style> -->
<table id="btable" style="width:100%">
<tr style="color: white;">
<th>url id ID</th>
<th>url</th>
<th>Regime</th>
<th>Jurisdiction</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
Script to populate json data
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type=text/javascript>
$(function() {
$('a#test').on('click', function(e) {
e.preventDefault()
$.get('/datahomepage',
function(data) {
// alert(data);
alert(data.length)
// console.console.log("hheh");
var tr;
for (var i=0;i<data.length;i++){
alert(data[i].url_id)
tr = $('<tr/>');
tr.append("<td>" + data[i].url_id+ "</td>");
tr.append("<td>" + data[i].url+ "</td>");
tr.append("<td>" + data[i].regime+ "</td>");
$('btable').append(tr);
}
});
// return false;
});
});
</script>

An obvious error is:
$('btable').append(tr);
which should be
$('#btable').append(tr);

Related

How can I set dynamic checkbox in web page

How can I set the dynamic checkbox into table rows when the data given from a modal using java script
function CreateCheckBox(){
//Second create a row
var row = document.tbody.tr;
row.className = 'gridrow';
//Third create td element
td = document.tbody.tr.td;
td.className = 'gridcell';
td.rowSpan = 1;
td.style.width = '80px';
//fourth create checkbox in that td element
var chkbox = document.createElement('input');
chkbox.type = "checkbox";
chkbox.id = "chk"
chkbox.name = "chk"
//Fifth add checkbox to td element
td.appendChild(chkbox);
//Add a td into a row
row.appendChild(td);
//Finally added to the form to print
}
<table
id="example"
class="form-table"
class="display select"
cellspacing="2"
cellpadding="10">
<thead>
<tr>
<th>CID</th>
<th>Name</th>
<th>Address</th>
<th>TP</th>
</tr>
</thead>
<tbody
id="tableB"
data-toggle="checkbox"
onclick="CreateCheckBox()">
</tbody>
</table>
but I cant get check box when the entered data from a model in web page.. this is table in index page..
After that I coded java script for data adding in table
Every time you want to add any row call createCheckBox with the excepted parameters.Hope it will work.
function createCheckBox(cid, name, address, tp) {
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + cid + "</td><td>" + name + "</td> <td>" + address + "</td><td>" + tp + "</td></tr>";
$(markup).appendTo("#example tbody");
}
createCheckBox(1, 'fafa', 'add', 'Tp1');
createCheckBox(2, 'fafa2', 'add2', 'Tp12');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="example" class="form-table display select" cellspacing="2" cellpadding="10">
<thead>
<tr>
<th>Checkbox</th>
<th>CID</th>
<th>Name</th>
<th>Address</th>
<th>TP</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
At the end of the script, I call createCheckBox two times with different value. So you can notice two rows in the table.

Is there a way of obtaining the value of the TH when hoovering over a TD in a table on HTML? [duplicate]

This question already has answers here:
How can I get the corresponding table header (th) from a table cell (td)?
(6 answers)
Closed 4 years ago.
I am trying to obtain the value of a TH after hoovering over its TD. I am able to obtain the value of the TD data cell when I hoover over it but cannot find a way to get the value for the TH.
This javascript allows me to click on the TD to obtain the entire row of values or hoover over a particular cell to get the value of it. However, I can't seem to find a way to get the TH.
$('#grid').click(function(evt) {
var row = $(evt.target).parent('tr'); // Get the parent row
var cell = $(evt.target); //Get the cell
alert('Row data: ' + row.text());
alert('Cell data: ' + cell.text());
});
$('#grid').on('mouseenter', 'td', function() {
console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div id="grid">
<table id="table1" border="1">
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
<tr>
<td>101</td>
<td>Jackie</td>
</tr>
<tr>
<td>102</td>
<td>Thomas</td>
</tr>
</tbody>
</table>
Rather than using javascript or jquery to traverse the DOM to find the th involved- you could use a HTML5 data-attribute and set the vvalue for each td - then show that on the click (here i am consoling it for the snippet).
$('#table td').on('click', function() {
let col = $(this).attr('data-col');
let content = $(this).text();
console.log(col + ": " + content);
});
table {
border-collapse: collapse;
}
th {
border: solid 1px #d4d4d4;
border-bottom-width: 2px;
padding: 5px 10px
}
td {
border: solid 1px #d4d4d4;
padding: 5px 10px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
<tr>
<td data-col="ID">101</td>
<td data-col="Name">Jackie</td>
</tr>
<tr>
<td data-col="ID">102</td>
<td data-col="Name">Thomas</td>
</tr>
</tbody>
</table>
Alternatively - you could have an array of the th contents (espescially if you create the table dynamically) - then on the click of the td - get its index in its tr (again you could store this in a data-attribute - or as an id - then use that index to reference the array.
This ouwl be the better method use an array or object to create the table dynamically and then you already have the data source to reference the content from.
var columns = ['ID','Name'];
$('#table td').on('click', function() {
let index = parseInt($(this).attr('data-index'));
let col = columns[index];
let content = $(this).text();
console.log(col + ": " + content);
});
table {
border-collapse: collapse;
}
th {
border: solid 1px #d4d4d4;
border-bottom-width: 2px;
padding: 5px 10px
}
td {
border: solid 1px #d4d4d4;
padding: 5px 10px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
<tr>
<td data-index='0'>101</td>
<td data-index='1'>Jackie</td>
</tr>
<tr>
<td data-index='0'>102</td>
<td data-index='1'>Thomas</td>
</tr>
</tbody>
</table>
Based on thread linked in the comments, Ive created below code.
This console logs the text value of the TH and the value of the TD on mouseover.
$('#grid').click(function(evt) {
var row = $(evt.target).parent('tr'); // Get the parent row
var cell = $(evt.target); //Get the cell
alert('Row data: ' + row.text());
alert('Cell data: ' + cell.text());
});
$('#grid').on('mouseenter', 'td', function() {
var $td = $(this),
$th = $td.closest('table').find('th').eq($td.index());
console.log($th.text() + ": " + $td.text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="grid">
<table id="table1" border="1">
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
<tr>
<td>101</td>
<td>Jackie</td>
</tr>
<tr>
<td>102</td>
<td>Thomas</td>
</tr>
</tbody>
</table>
</div>
Find child-index-number of the td element under the tr element.
Find the th element by index.
//Find table
var table = document.getElementById('table');
//Hover event callback
function hoverTDEvent(evt) {
//Only run on td
if (evt.target.nodeName.toLowerCase() != 'td') {
return false;
}
//Find relative index
var index = Array.prototype.slice.call(evt.target.parentNode.children).indexOf(evt.target);
//Find th by index and log contents
console.log(table.querySelectorAll("th")[index].textContent,evt.target.textContent);
}
//Bind event
table.addEventListener("mousemove", hoverTDEvent);
<table id="table" border="1">
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
<tr>
<td>101</td>
<td>Jackie</td>
</tr>
<tr>
<td>102</td>
<td>Thomas</td>
</tr>
</tbody>
</table>
Notice that this wont work if you use the colspan property.

DataTable pagination is not working?

I have my html page which contains a table. I use dataTable plugin for pagination.1
1https://datatables.net/examples/basic_init/alt_pagination.html
My html as follows.
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"
type="text/javascript"></script>
<script type="text/javascript"
src=" https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript"
src=" https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script>
<style type="text/css">
table, th,td{
border: 1px solid black;
text-align:center;
}
#clients_data {
margin-bottom:100px;
}
</style>
<meta charset="UTF-8">
<link rel="stylesheet"
href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<title>Clients</title>
</head>
<body>
<table style="width: 100%" id="clients_data" class="display" >
<caption>Clients</caption>
<thead>
<tr>
<th>Clients</th>
<th>Number of Sites</th>
<th>Reset the Processing</th>
</tr>
</thead>
</table>
<table style="width: 100%" id="machines_data">
<caption>Machines</caption>
<thead>
<tr>
<th>Number</th>
<th>Machine Name</th>
</tr>
</thead>
</table>
<script type="text/javascript">
$(document).ready(function() {
loadCustomers();
loadMachines();
});
function loadCustomers() {
$
.ajax({
type : 'GET',
url : 'http://localhost:8080/cache/getCustomers',
dataType : 'json',
success : function(data) {
var rows = [];
$
.each(
data,
function(id, value) {
rows
.push(' <tbody><tr><td><a href="clientSiteInfo.html?client='
+ id
+ '">'
+ id
+ '</td><td>'
+ value
+ '</td><td><button type="button" onclick="reset(\''
+ id
+ '\')">Reset</td></tr> </tbody>');
});
$('#clients_data').append(rows.join(''));
$('#clients_data').DataTable({
"pagingType" : "full_numbers"
});
}
});
};
.......
this loads data, but pagination is not working. means when I set 10 entries per page, it shows all entries..I have attached the screenshot. AM i missing any other plugin?
But in the mentioned tutorial, it says I need to use "pagingType" : "full_numbers" attribute only..
The pagination works perfectly as expected. The problem is that you wrongly insert a <tbody> section for each row. And since you only can have one <tbody> per DataTable the shown pagination will be based on the very first row in the dataset, thus always showing one page in total.
You could do this instead :
rows
.push(' <tr><td><a href="clientSiteInfo.html?client=' +
id +
'">' +
id +
'</td><td>' +
value +
'</td><td><button type="button" onclick="reset(\'' +
id +
'\')">Reset</td></tr> ');
});
and
$('#clients_data').append('<tbody>'+rows.join('')+'</tbody>');
but you should really consider using columns instead.

How to populate html table using javascript without using div?

I am trying to fill html table(my table got 3 columns) with data from json using javascript but the data never get filled using div method! could any tell me how to fill content of table rows using without using div ?
for(i in json)
{
var div = "<tr id=\""+i+"\">\n" +
"<td>"+i+"</td>\n" +
"<td><img src=\""+ json[i].thumb +"\" height=\"42\" width=\"42\"></td>\n" +
"<td>\n" +
"" + json[i].title + "<br> \n" +
"<br></td></tr>\n\n";
$("#myDiv").append(div);
}
Table to be filled:
<table id="list" cellspacing="0" border="1">
<tr>
<th>Item#</th>
<th>Logo</th>
<th>Description</th>
</tr>
<div id='myDiv'></div>
</table>
This Your new table:
<table id="list" cellspacing="0" border="1">
<thead>
<tr>
<th>Item#</th>
<th>Logo</th>
<th>Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
And code:
var html = '';
for(var i in json)
{
html += '<tr id="'+i+'">';
html += '<td>'+i+'</td>';
html += '<td><img src="'+json[i].thumb+'" height="42" width="42"></td>';
html += "<td>";
html += "" + json[i].title + "<br/><br/>";
html += '</td>';
html += '</tr>';
}
$('#list > tbody').html(html);

tr:nth-child css zebra striping after xml jquery parsing

How do I apply styling to a table after parsing XML data into the table?
In the code below I Created the first three rows of a table using html, then the additional rows were created by parsing XML. however the Zebra stripe styling was not applied to the table after the jquery call. I've tried my best to find the problem with my code but I'm stumped.
Here's a code sample of my html:
<head>
<title>Football Players</title>
<style>
table{
border-collapse: collapse;
border: solid 1px #dddddd;
width: 500px;
}
th{
text-align: left;
}
</style>
</head>
<body>
<table>
<tbody>
<tr>
<th>Name</th>
<th>Club</th>
<th>Number</th>
<th>Country</th>
</tr>
<tr>
<td>Lionel Messi</td>
<td>Barcelona</td>
<td>10</td>
<td>Argentina</td>
</tr>
<tr>
<td>Juan Mata</td>
<td>Manchester United</td>
<td>8</td>
<td>Spain</td>
</tr>
</tbody>
</table>
</body>
And the following is a snippet of my JQuery:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "football_player.xml",
dataType: "xml",
success: processXML
});
function processXML(xml) {
$(xml).find("football_player").each(function () {
$("table tbody").append("<tr class = 'myClass'>");
$("table tbody").append("<td>" + $(this).find("name").text() + "</td>");
$("table tbody").append("<td>" + $(this).find("club").text() + "</td>");
$("table tbody").append("<td>" + $(this).find("number").text() + "</td>");
$("table tbody").append("<td>" + $(this).find("country").text() + "</td>");
$("table tbody").append("</tr>");
});//close processXML
$("table tbody tr:nth-child(odd)").css("background-color", "#dddddd");
}
});//close document.ready()
And lastly the XML file:
<football_players>
<football_player>
<name>Cristiano Ronaldo</name>
<club>Real Madrid</club>
<number>7</number>
<country>Portugal </country>
</football_player>
<football_player>
<name>Fernando Torres </name>
<club>Chelsea </club>
<number>9</number>
<country>Spain</country>
</football_player>
<football_player>
<name>Iker Casillas</name>
<club>Real Madrid </club>
<number>1</number>
<country>Spain</country>
</football_player>
<football_player>
<name>David Beckham</name>
<club>Los Angeles Galaxy</club>
<number>23</number>
<country>England</country>
</football_player>
</football_players>
Checking the console is always a good idea,The problem in your code probably is in the function processXML(xml).This is beacause your <tr> were closed before adding <td>.Hence it was not applying the color.
Change it to..
function processXML(xml) {
$(xml).find("football_player").each(function () {
$("table tbody").append("<tr class = 'myClass'>"+"<td>" +
$(this).find("name").text() + "</td>"+"<td>" + $(this).find("club").text() + "</td>"+"<td>" + $(this).find("number").text() + "</td>"+"<td>" + $(this).find("country").text() + "</td>"+"</tr>");
});//close processXML
$("table tbody tr:nth-child(odd)").css("background-color", "#dddddd");
}
Thanks to Varun I came up with the following which worked:
function processXML(xml) {
$(xml).find("football_player").each(function () {
$("table tbody").append("<tr class = 'myClass'><td>" + $(this).find("name").text() + "</td><td>" + $(this).find("club").text() + "</td><td>" + $(this).find("number").text() + "</td><td>" + $(this).find("country").text() + "</td></tr>");
});
$("table tbody tr:nth-child(odd)").css("background-color", "#dddddd");
}

Categories

Resources