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");
}
Related
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);
I am making multiple ajax request using JQuery to populate table rows. How to sort the table column. I am using the first API to fetch all symbol's value. The second API is used to find the values of that particular symbol. These values are appended into table. I want to use sorting on columns of the table.
tablesorter() is is a function which sorts table is not working. This is working fine for a simple table.
Here is my code.
<script type="text/javascript">
// HTTPRequest
var value = [];
$.ajax({
method: "GET",
url: "https://api.binance.com/api/v1/exchangeInfo"
})
.done(function(data){
data.symbols.forEach(function(element, index) {
value[index] = element.symbol;
$(".tablefriendsname").append("<tr><td>" + element.symbol + "</td></tr>");
$.ajax({
method: "GET",
url: "https://api.binance.com/api/v1/ticker/24hr?symbol=" + data.symbols[index].symbol
})
.done(function(data2){
$(".tablefriendsname2").append("<tr><td>" + data2.priceChange + "</td></tr>");
$(".priceChangePercent").append("<tr><td>" + data2.priceChangePercent + "</td></tr>");
$(".weightedAvgPrice").append("<tr><td>" + data2.weightedAvgPrice + "</td></tr>");
$(".prevClosePrice").append("<tr><td>" + data2.prevClosePrice + "</td></tr>");
$(".lastPrice").append("<tr><td>" + data2.lastPrice + "</td></tr>");
$(".lastQty").append("<tr><td>" + data2.lastQty + "</td></tr>");
$(".bidPrice").append("<tr><td>" + data2.bidPrice + "</td></tr>");
$(".bidQty").append("<tr><td>" + data2.bidQty + "</td></tr>");
$(".askPrice").append("<tr><td>" + data2.askPrice + "</td></tr>");
$(".askQty").append("<tr><td>" + data2.askQty + "</td></tr>");
$(".openPrice").append("<tr><td>" + data2.openPrice + "</td></tr>");
$(".highPrice").append("<tr><td>" + data2.highPrice + "</td></tr>");
$(".lowPrice").append("<tr><td>" + data2.lowPrice + "</td></tr>");
$(".volume").append("<tr><td>" + data2.volume + "</td></tr>");
$(".quoteVolume").append("<tr><td>" + data2.quoteVolume + "</td></tr>");
$(".openTime").append("<tr><td>" + data2.openTime + "</td></tr>");
$(".closeTime").append("<tr><td>" + data2.closeTime + "</td></tr>");
$(".firstId").append("<tr><td>" + data2.firstId + "</td></tr>");
$(".lastId").append("<tr><td>" + data2.lastId + "</td></tr>");
$(".count").append("<tr><td>" + data2.count + "</td></tr>");
$('#myTable').trigger('update');
}) // closed Inner done
}) // CLOSE FOREACh
}); // CLOSE outer DONE
<!-- Sorting Columns -->
$(document).ready(function()
{
$("#myTable").tablesorter();
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.29.5/js/jquery.tablesorter.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Crypto Api Fetch</title>
</head>
<body>
<table id="myTable" class="tablesorter">
<thead>
<tr>
<th class="">symbol</th>
<th class="">priceChangePercent</th>
<th class="">weightedAvgPrice</th>
<th class="">prevClosePrice</th>
<th class="">lastPrice</th>
<th class="">lastQty</th>
<th class="">bidPrice</th>
<th class="">bidQty</th>
<th class="">askPrice</th>
<th class="">askQty</th>
<th class="">openPrice</th>
<th class="">highPrice</th>
<th class="">lowPrice</th>
<th class="">volume</th>
<th class="">quoteVolume</th>
<th class="">openTime</th>
<th class="">closeTime</th>
<th class="">firstId</th>
<th class="">lastId</th>
<th class="">count</th>
</tr>
</thead>
<tbody>
<tr class="">
<td class="tablefriendsname"></td>
<td class="tablefriendsname2"></td>
<td class="priceChangePercent"></td>
<td class="weightedAvgPrice"></td>
<td class="prevClosePrice"></td>
<td class="lastPrice"></td>
<td class="lastQty"></td>
<td class="bidPrice"></td>
<td class="bidQty"></td>
<td class="askPrice"></td>
<td class="askQty"></td>
<td class="openPrice"></td>
<td class="highPrice"></td>
<td class="lowPrice"></td>
<td class="volume"></td>
<td class="quoteVolume"></td>
<td class="openTime"></td>
<td class="closeTime"></td>
<td class="firstId"></td>
<td class="lastId"></td>
<td class="count"></td>
</tr>
</tbody>
</table>
</body>
</html>
Load jQuery first.
Don't append a row into a cell; create a row string, add each cell, then append it to the table:
.done(function(data2){
var tr = '<tr><td class="symbol">' + element.symbol + '</td>';
// array of each table column in order
['priceChangePercent', ..., 'count'].forEach(item => {
tr += '<td class="' + item + '">' + data2[item] + '</td>';
});
$('#mytable).append(tr).trigger('update');
});
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.
here is the fiddle
https://jsfiddle.net/shaswatatripathy/enq0kfqL/2/
how to write the remove function and how to add a css class to a row which is clicked .
1.when i click remove the clicked row should get removed
when i click the row - row should get highlightrow css class attached
also have to check if the table has any rows or not and put it in a var
at a time only one row should be in red (clicked row) if no row is selected the remove button should not be visible
HTML
col1header
col2header
CSS
.visibilityHide {
visibility: hidden;
}
.highlightRow{
color:red;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
JS or Jquery
function add()
{var addRow1;
var addRow2;
addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
$("#myTableid tbody").append(addRow1);
$("#myTableid tbody").append(addRow2);
}
function remove()
{
}
function getdetails(row)
{
$('#removerow').css('visibility', 'visible');
}
This is the updated javascript code. This will meet all your requirements.
function add()
{
var addRow1;
var addRow2;
addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
$("#myTableid tbody").append(addRow1);
$("#myTableid tbody").append(addRow2);
}
function remove()
{
$(".highlightRow").remove();
$('#removerow').addClass('visibilityHide');
$("#dropDown").prop("disabled", $("#myTableid tbody tr").length > 0);
}
function getdetails(row)
{
$('#removerow').toggleClass('visibilityHide', $("#myTableid tbody tr").length === 0);
$(".highlightRow").removeClass("highlightRow");
$(row).addClass("highlightRow");
}
Try this one. if it'll work
function add(){
var addRow1;
var addRow2;
addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
$("#myTableid tbody").append(addRow1);
$("#myTableid tbody").append(addRow2);
}
function remove(){
$('.removeClass').remove(); //remove clicked row
if($('table tbody tr').length <=0){
$('#removerow').hide();
}
if($('table tbody tr').length===0) {
alert('This last child has been removed');
$("#dropDown").prop("disabled", false);
}
}
function getdetails(row){
$('#removerow').show();
$(row).addClass('removeClass'); //add class on clicked row
}
.highlightRow{
color:red;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
/* styling for added class so that it looks something different when class added */
.removeClass{
color:red;
}
#removerow {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table id="myTableid">
<thead>
<th>
col1header
</th>
<th>
col2header
</th>
</thead>
<tbody>
</tbody>
</table>
<input type="button" id ="addrows" value="add" onclick="add()" />
<input type="button" id="removerow" value="remove" onclick="remove()" class="visibilityHide" />
Checking if the row is the last one is this part of the code
if($('table tbody tr').length==0) {
alert('This last child has been removed');
$("#dropDown").prop("disabled", false);
}
Do it like below (All solutions what you asked for):-
function add(){
var addRow1;
var addRow2;
addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
$("#myTableid tbody").append(addRow1);
$("#myTableid tbody").append(addRow2);
}
function remove(){
var index = parseInt($('.removeClass').index())+1;
$('.removeClass').remove(); //remove clicked row
$('.removed_row').html("<strong>row number "+index+ " removed</strong>");
if($('table tbody tr').length <=0){
$('#removerow').hide();
}
}
function getdetails(row){
$('#removerow').css('display', 'block');
$('.removeClass').removeClass('removeClass');
$(row).addClass('removeClass'); //add class on clicked row
}
.visibilityHide {
display: none;
}
.highlightRow{
color:red;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
/* styling for added class so that it looks something different when class added */
.removeClass{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTableid">
<thead>
<th>
col1header
</th>
<th>
col2header
</th>
</thead>
<tbody>
</tbody>
</table>
<input type="button" id ="addrows" value="add" onclick="add()" />
<input type="button" id="removerow" value="remove" onclick="remove()" class="visibilityHide" />
<br>
<br>
<br>
<div class="removed_row"></div>
You can check the answer in my update:
function remove()
{
window.selectedRow.remove();
$('#removerow').css('visibility', 'hidden');
}
function getdetails(row)
{
removeHighlights();
window.selectedRow = row;
row.classList.add("highlightRow");
$('#removerow').css('visibility', 'visible');
}
function removeHighlights() {
var elements = document.getElementsByClassName("highlightRow");
while(elements.length > 0){
elements[0].classList.remove('highlightRow');
}
}
https://jsfiddle.net/g63zpuuz/
I am very new to jQuery,so bear with me if it seems to be silly question.
I have an table with many TD's in each row.I need to convert an TD element with plain text belonging to a particular column into an TD with Select element with pre-populated options,when user clicks that TD of that column using jQuery.
You can't convert the td into a select, because that would result in an invalid document. What you can do, is put the select within the td. E.g.:
$('selector for the td in question').html(
'<select>' +
'<option value="1">One</option>' +
'<option value="2">Two</option>' +
'<option value="3">Three</option>' +
'</select>'
);
Here's a complete example, also demonstrating event delegation: Live Copy
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<meta charset=utf-8 />
<title>Select in Cell</title>
<style>
.type {
cursor: pointer;
white-space: nowrap;
}
table {
border: 1px solid #aaa;
border-collapse: collapse;
}
td, th {
border: 1px solid #aaa;
padding: 2px;
}
</style>
</head>
<body>
<p>Click cells in the type column.</p>
<table id="theTable">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="type">Thingy</td>
<td>Blah</td>
</tr>
<tr>
<td class="type">Widget</td>
<td>Blah</td>
</tr>
<tr>
<td class="type">Whatsit</td>
<td>Blah</td>
</tr>
</tbody>
</table>
<script>
(function() {
$("#theTable").on("click", ".type", function() {
var $this = $(this),
current = $this.text(),
select;
if ($this.find("select").length) {
return;
}
select = $(
'<select>' +
'<option>Thingy</option>' +
'<option>Widget</option>' +
'<option>Whatsit</option>' +
'</select>'
);
$this.html(select);
select.val(current).focus();
});
$("#theTable").on("blur", ".type select", function() {
var $this = $(this);
$this.closest('td').text($this.val());
});
})();
</script>
</body>
</html>
Interesting task. Try this solution:
$('table').on('click', 'td', function(e) {
if ($(this).data('converted')) {
e.stopPropagation();
return;
}
$(this).data('converted', $(this).text());
var rowIndex = this.parentNode.rowIndex,
index = this.cellIndex + 1,
options = $(e.delegateTarget).find('td:nth-child(' + index +')').map(function(i) {
var text = $(this).data('converted') || $(this).text();
return '<option ' + (rowIndex == i ? 'selected' : '') + '>' + text + '</option>';
}).get();
$(this).html('<select>' + options.join('') + '</select>');
});
Demo: http://jsfiddle.net/As9dY/2/
Q: How to add a select dropdown to a TD dynamically?
Here's how you do it:
HTML:
<table>
<tr><th>Column A</th><th>Column B</th></tr>
<tr><td>1</td><td>6</td></tr>
<tr><td>2</td><td>7</td></tr>
<tr><td>3</td><td>8</td></tr>
<tr><td>4</td><td id="nine">9</td></tr>
<tr><td>5</td><td>10</td></tr>
</table>
jQuery:
$(document).ready(function() {
var isAppended = false;
var select = "<select name='mySelect'>" +
"<option value='volvo'>Volvo</option>" +
"<option value='saab'>Saab</option>" +
"<option value='opel'>Opel</option>" +
"<option value='audi'>Audi</option>" +
"</select>";
$("#nine").click(function() {
if (!isAppended) {
$(this).append(select);
isAppended = true;
}
});
});
JSFIDDLE DEMO