I have designed a table with headers. I am appending dynamic rows <tr> to this table. While appending I am losing the order of the rows. Any suggestion or ideas as to how can I solve this problem? Thanks in advance.
<table id="myTable">
<thead>
<tr><td></td></tr><tr>
<th>Name</span></th>
<th>Description</span>
</th>
</tr>
</thead>
-- dynamic rows will come.
</table>
var html1 = '<tr id="1"><td>aaa</td><td>aaa</td></tr>'; // This position is fine
var html2 = '<tr id="3"><td>bbb</td><td>bbb</td></tr>'; // This one is having id '3', it should go to 3rd position. when 2nd comes.
var html3 = '<tr id="2"><td>ccc</td><td>ccc</td></tr>'; // This should go to 2nd position.
$('#myTable').append(html1);
$('#myTable').append(html2);
$('#myTable').append(html3);
Desired Output :
<table id="myTable">
<thead>
<tr><td></td></tr><tr>
<th>Name</span></th>
<th>Description</span>
</th>
</tr>
</thead>
<tr id="1">
<td>aaa</td>
<td>aaa</td>
</tr>
<tr id="2">
<td>ccc</td>
<td>ccc</td>
</tr>
<tr id="3">
<td>bbb</td>
<td>bbb</td>
</tr>
</table>
This you will do. Add a sorting function and then call that function as described in below link.
Added snippet based on Jquery content sorting link:- https://www.shift8web.ca/2017/01/use-jquery-sort-reorganize-content/
var html1 = '<tr id="1"><td>aaa</td><td>aaa</td></tr>'; // This position is fine
var html2 = '<tr id="3"><td>bbb</td><td>bbb</td></tr>'; // This one is having id '3', it should go to 3rd position. when 2nd comes.
var html3 = '<tr id="2"><td>ccc</td><td>ccc</td></tr>'; // This should go to 2nd position.
$('#myTable').append(html1);
$('#myTable').append(html2);
$('#myTable').append(html3);
var i;
var htmlcontent = $('#myTable').html();
$('#myTableOriginalContent ').html( $('#myTable').html())
sortMeBy('id', 'myTable', 'tr', 'asc')
function sortMeBy(arg, sel, elem, order) {
var $selector = $('#'+sel),
$element = $selector.children(elem);
$element.sort(function(a, b) {
var an = parseInt(a.getAttribute(arg)),
bn = parseInt(b.getAttribute(arg));
if (order == "asc") {
if (an > bn)
return 1;
if (an < bn)
return -1;
} else if (order == "desc") {
if (an < bn)
return 1;
if (an > bn)
return -1;
}
return 0;
});
$element.detach().appendTo($selector);
}
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Original Content
<table id="myTableOriginalContent">
<thead>
<tr><td></td></tr>
<tr>
<th><span>Name</span></th>
<th><span>Description</span></th>
</tr>
</thead>
</table>
Desired Result
<table id="myTable">
<thead>
<tr><td></td></tr>
<tr>
<th><span>Name</span></th>
<th><span>Description</span></th>
</tr>
</thead>
</table>
</body>
</html>
Change $('#myTable').append(html3); to $(html3).insertAfter('#1'). Also note that you'll need a tbody element after the thead to contain your rows, but I would imagine the browser will be inserting one for you automatically. Try this:
var html1 = '<tr id="1"><td>aaa</td><td>aaa</td></tr>';
var html2 = '<tr id="3"><td>bbb</td><td>bbb</td></tr>';
var html3 = '<tr id="2"><td>ccc</td><td>ccc</td></tr>';
$('#myTable tbody').append(html1).append(html2);
$(html3).insertAfter('#1');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<td></td>
</tr>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody></tbody>
</table>
The logic is you append all dynamic table rows then reorder them based on the attribute of the id.
Sorting code source: Using jquery, how do you reorder rows in a table based on a TR attribute?
I just modified it a little.
var html1 = '<tr id="1"><td>aaa</td><td>aaa</td></tr>'; // This position is fine
var html2 = '<tr id="3"><td>bbb</td><td>bbb</td></tr>'; // This one is having id '3', it should go to 3rd position. when 2nd comes.
var html3 = '<tr id="2"><td>ccc</td><td>ccc</td></tr>'; // This should go to 2nd position.
var html4 = '<tr id="5"><td>5th</td><td>5th</td></tr>'; // This should go to 5th position.
var html5 = '<tr id="4"><td>4th</td><td>4th</td></tr>'; // This should go to 4th position.
$('#myTable tbody').append(html1);
$('#myTable tbody').append(html2);
$('#myTable tbody').append(html3);
$('#myTable tbody').append(html4);
$('#myTable tbody').append(html5);
var $table=$('#myTable');
var rows = $table.find('tr').get();
rows.sort(function(a, b) {
var keyA = $(a).attr('id');
var keyB = $(b).attr('id');
if (keyA > keyB) return 1;
if (keyA < keyB) return -1;
return 0;
});
$.each(rows, function(index, row) {
$table.children('tbody').append(row);
});
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<table id="myTable">
<thead>
<tr><td></td></tr><tr>
<th>Name</span></th>
<th>Description</span>
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Simple just you are calling wrong way call this way
$('#myTable').append(html1);
$('#myTable').append(html3);
$('#myTable').append(html2);
Complete Code
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th>Name</span></th>
<th>Description</span>
</th>
</tr>
</thead>
</table>
</body>
</html>
<script type="text/javascript">
$( document ).ready(function() {
var html1 = '<tr id="1"><td>aaa</td><td>aaa</td></tr>';
var html2 = '<tr id="3"><td>bbb</td><td>bbb</td></tr>';
var html3 = '<tr id="2"><td>ccc</td><td>ccc</td></tr>';
$('#myTable thead').after(html1,html3,html2);
});
</script>
Try Following
Add <tbody> in table & append rows
var html1 = '<tr id="1"><td>aaa</td><td>aaa</td></tr>'; // This position is fine
var html2 = '<tr id="3"><td>bbb</td><td>bbb</td></tr>'; // This one is having id '3', it should go to 3rd position. when 2nd comes.
var html3 = '<tr id="2"><td>ccc</td><td>ccc</td></tr>'; // This should go to 2nd position.
$('#myTable tbody').append(html1);
$('#myTable tbody').append(html2);
$('#myTable tbody').append(html3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr><td></td></tr><tr>
<th>Name</span></th>
<th>Description</span>
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Related
I have a table in html.
I want that when I mouse over a cell, it pop-ups a text. The text popped-up, should depend of the text inside of the cell.
Example of an html table:
City number
Paris 1454
Madrid 1345
Roma 684
If I mouseover a City (Paris), it should pop-up the country (France).
I have seen partial solutions, (
https://www.w3schools.com/howto/howto_js_popup.asp
https://www.w3schools.com/css/css_tooltip.asp), but I don´t know how to solve the conditional part of the pop-up.
Thank you
I think that you need a hover
The <abbr title="World Health Organization">WHO</abbr> was founded in 1948.
https://www.w3schools.com/tags/tag_abbr.asp
There is an easier way to have "hover-popups" in HTML. You can add a title property to set the text shown in the popup:
<td title="France">Paris</td>
You can also set this via JavaScript:
td.title = "France"
I don't know if that is what you're looking for, but if it is, it's easier that way
Supposing a DOM like that :
<table>
<thead>
<tr>
<th>City</th>
<th scope="col">Number</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Paris </th>
<td>1454</td>
</tr>
<tr>
<th scope="row">Madrid</th>
<td>1345</td>
</tr>
<tr>
<th scope="row">Roma</th>
<td>684</td>
</tr>
</tbody>
</table>
Assuming you have a JS code that show the popup on hover.
You can use the data attribute to set the country on each city cell:
<th scope="row" data-country="France">Paris</th>
And patch the JS code to use it:
const elts = document.getElementsByTagName('th');
for (let elt of elts) {
elt.addEventListener("mouseover", (evt) => {
const country = evt.target.getAttribute('data-country');
yourPopupScript(country); // this trigger your popup, and you can write the country into
});
}
Static generated Table:-
var list = [{
city: "Italy",
country: "Rome"
}, {
city: "Belgium",
country: "Brussels"
}];
var statusCol = "";
var table = '<table><tr><th>City</th><th>Country</th></tr>';
var ID = 0;
for (var i = 0; i < list.length; i++) {
var row = "<tr class='staff-row' >";
row += '<td title=' + list[i].city + '>' + list[i].city + '</td>';
row += '<td title=' + list[i].country + '>' + list[i].country + '</td>'
row += "</tr>"
ID++;
table += row;
}
table += '</table>';
$('#DisplayTable').html(table);
$('#DisplayTable').tooltip({
'show': true,
'selector': '.staff-row',
'placement': 'bottom',
'title': function(event) {
var $this = $(this);
var tds = $this.find('td');
return
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href='http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css' />
<script src='http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js'></script>
Static Table:-
<table class="popup">
<tr onclick="myFunction(event)">
<th title="City">City</th>
<th title="Country">Country</th>
</tr>
<tr>
<td title="Delhi">Delhi</td>
<td title="India">India</td>
</tr>
<tr>
<td title="Paris">Paris</td>
<td title="France">France</td>
</tr>
</table><br /> Dynamic Table:-
<div id="DisplayTable"></div>
I have a table and the data in this table is from database. I want to click this row and transfer it to other table. I can transfer this row using input checkbox. I'd realize that it will be easy and convenient to transfer the rows by just clicking it without checkbox. I have a hard time converting it to a clickable instead of checkbox.
I tried using this code
$(document).ready(function() {
$( "#table1 tbody tr" ).on( "click", function( event ) {
var product = $(this).attr('data-product');
var price = $(this).attr('data-price');
var barcode = $(this).attr('data-barcode');
var unit = $(this).attr('data-unt');
var qty = prompt("Enter number of items",1);
var total = qty*price;
$('#tableData').append("<tr><td>"+barcode+"</td><td>"+product+"</td><td>₱"+price+"</td><td>"+unit+"</td><td>"+qty+"</td><td>₱"+total+"</td><tr>");});
This is my jquery that I wanted to convert into clickable code.
function add(){
$('input:checked[name=tab1]').each(function() {
var product = $(this).attr('data-product');
var price = $(this).attr('data-price');
var barcode = $(this).attr('data-barcode');
var unit = $(this).attr('data-unt');
var qty = prompt("Enter number of items",1);
var total = qty*price;
$('#tableData').append("<tr><td>"+barcode+"</td><td>"+product+"</td><td>₱"+price+"</td><td>"+unit+"</td><td>"+qty+"</td><td>₱"+total+"</td><tr>"); });}
My PHP code.
<?php
include('server/connection.php');
if (isset($_POST['products'])){
$name = mysqli_real_escape_string($db,$_POST['products']);
$num = 1;
$show = "SELECT * FROM products WHERE product_name LIKE '$name%' ";
$query = mysqli_query($db,$show);
if(mysqli_num_rows($query)>0){
while($row = mysqli_fetch_array($query)){
$total = $num*$row['sell_price'];
echo "<tr id='sas'><td>".$row['id']."</td><td>".$row['product_name']."</td>";
echo "<td>₱".$row['sell_price']."</td>";
echo "<td>".$row['unit']."</td>";
echo "<td>".$row['quantity']."</td>";
echo "<td><input type='checkbox' name='tab1' data-barcode='".$row['id']."' data-product='".$row['product_name']."' data-price='".$row['sell_price']."' data-unt='".$row['unit']."' data-qty='".$num."' data-total='".$total."'/></td></tr>";
}
}
else{
echo "<td></td><td>No Products found!</td><td></td>";
}
}
My Table
<table id="table1">
<thead>
<tr>
<td>Barcode</td>
<td>Product Name</td>
<td>Price</td>
<td>Unit</td>
<td>Stocks</td>
<td>Action</td>
</tr>
</thead>
<tbody id="products">
</tbody>
</table>
<table id="table2">
<thead>
<tr>
<th>Barcode</th>
<th>Description</th>
<th>Price</th>
<th>Unit</th>
<th>Qty</th>
<th>Sub.Total</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
I expect by just clicking the row it will automatically transfer to the table2 with a dialog box using prompt that will ask for quantity of a product then it will be printed to the second table along with the entire row.
This is my UI with css.
You are on the right way, just fix JS selectors using $(this) and formating the price...
$("#table1 .js-add").on("click", function() {
var target = $(this);
var product = target.attr('data-product');
var price = target.attr('data-price');
var barcode = target.attr('data-barcode');
var unit = target.attr('data-unt');
var qty = prompt("Enter number of items", 1);
var total = qty * price;
$('#tableData').append("<tr><td>" + barcode + "</td><td>" + product + "</td><td>" + price + "</td><td>" + unit + "</td><td>" + qty + "</td><td>" + total.toFixed(2) + "</td><tr>");
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<table id="table1" class="table">
<thead>
<tr>
<th>Barcode</th>
<th>Product Name</th>
<th>Price</th>
<th>Unit</th>
<th>Stocks</th>
<th>Action</th>
</tr>
</thead>
<tbody id="products">
<tr>
<td>123412</td>
<td>Test</td>
<td>12.99</td>
<td>1</td>
<td>10</td>
<td>
<input name='tab1' type="checkbox" class='js-add' data-barcode="123412" data-product="Test" data-price="12.99" data-unt="1"/>
</td>
</tr>
</tbody>
</table>
<br>
<table id="table2" class="table">
<thead>
<tr>
<th>Barcode</th>
<th>Description</th>
<th>Price</th>
<th>Unit</th>
<th>Qty</th>
<th>Sub.Total</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
You need to use event.target instead of this in the function.
$(document).ready(function() {
$( "#table1 tbody tr" ).on( "click", function( event ) {
var target = event.target;
var product = target.attr('data-product');
var price = target.attr('data-price');
var barcode = target.attr('data-barcode');
var unit = target.attr('data-unt');
var qty = prompt("Enter number of items",1);
var total = qty*price;
$('#tableData').append("<tr><td>"+barcode+"</td><td>"+product+"</td><td>₱"+price+"</td><td>"+unit+"</td><td>"+qty+"</td><td>₱"+total+"</td><tr>");});
On tr click event, you are using data-product and other selectors. data-product is not defined for tr. You have to add data-product attribute for each row. You can refer this - JQuery: Find (the index of) a row with a specific data attribute value
Basically the same question as How can I get the corresponding table header (th) from a table cell (td)? but not jQuery specific.
From a given <td> is there an easy way to find the corresponding <th>?
<table width="100%" id="stock">
<tr>
<th>Name</th>
<th>Type</th>
<th>Quantity</th>
<th>Options</th>
</tr>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td>-1</td>
<td>...</td>
</tr>
I'd like something doing this:
document.getElementById('target').correspondingTH // would return HTMLObject <th>Type</th>
An ideal answer might contain both a jQuery way to do it and a vanilla one but I'm personally looking for a vanilla one.
Pure JavaScript's answer.
var index = Array.prototype.indexOf.call(your_td.parentNode.children, your_td)
var corresponding_th = document.querySelector('#your_table_id th:nth-child(' + (index+1) + ')')
As posted here in the more jQuery specifc question: https://stackoverflow.com/a/37312707/1524913
HTML table model gives easier solution. jquery in this case is more sophisticated. I tested following table:
<table style="width:100%" id="stock">
<tbody>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td>-1</td>
<td>...</td>
</tr>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td>-1</td>
<td>...</td>
</tr>
</tbody>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td colspan="2">-1</td>
<!--<td>...</td>-->
</tr>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Quantity</th>
<th>Options</th>
</tr>
</thead>
</table>
Script without jquery is simple and straightforward.
window.onload = function () {
var tbl = document.getElementById('stock');
var tds = document.getElementsByTagName('td');
for (var i = 0, td; td = tds[i]; ++i) {
td.onclick = function () {
var tr = this.parentNode;
console.log(tbl.rows[0].cells[this.cellIndex].innerHTML);
}
}
}
jquery also is useful.
$(document).ready(function () {
$('#stock td').click(function () {
console.log($(this).parents('table').find('tr:first-child').children('th:nth-child(' + (this.cellIndex + 1) + ')').html());
});
});
<thead> can be placed at the top, at the bottom, and between rows. thead inside tbody is obvious error but browser fixes it. Scripts work in any case.
I think you need to step through the TH colSpans to exactly match the TD
Try
function getHeadCell(td) {
var index = Array.prototype.indexOf.call(td.parentNode.children, td);
var table = td;
while (table && table.tagName != 'TABLE') table = table.parentNode;
var cx = 0;
for (var c = 0; cx <= index; c++) cx += table.rows[0].cells[c].colSpan;
return table.rows[0].cells[c - 1];
}
See https://jsfiddle.net/Abeeee/upt75s2x/34/ for a working example
i have a dynamic table like this:
<table cellspacing="0" cellpadding="0">
<col width="80" span="3">
<tr id="id-1">
<th colspan="3" width="240">TITLE-1</th>
</tr>
<tr>
<td>val-1</td>
<td>val-2</td>
<td>val-3</td>
</tr>
<tr id="id-1">
<th colspan="3">TITLE-1</th>
</tr>
<tr>
<td>val-2</td>
<td>val-2</td>
<td>val-3</td>
</tr>
<tr id="id-2">
<th colspan="3">TITLE-2</th>
</tr>
<tr>
<td>val-1</td>
<td>val-2</td>
<td>val-2</td>
</tr>
</table>
In this table is 3 TR element with same ID. i want to remove all TR except first TR.
If not is duplicate IDs nothing change with this TR.
And i need also: in TR's is 3 td's. result must be next. if value is same group this td's:
<tr>
<td>val-2</td>
<td>val-2</td>
<td>val-3</td>
</tr>
result
<tr>
<td colspan="2">val-2</td>
<td>val-3</td>
</tr>
tnx
i changed id > class
$(".idxx:gt(0)").remove();
I did a function to parse tr's and td's. See here http://jsfiddle.net/mig1098/qo4xvqjm/ :
var mapTable={
_tr:function(){
var tabletr = $('table tr');
var compareid = '';
tabletr.each(function(){
var id = $(this).attr('id');
if(typeof id != 'undefined'){
if(compareid == ''){
compareid = id;
}else if(compareid == id){
$('#'+id).next().remove();
$('#'+id).remove();
}
}
});
},
_td:function(){
tabletr = $('table tr');
tabletr.each(function(){
var tdtext = {"obj":"","txt":"","count":1};
console.log($(this).find('th').text());
$(this).find('td').each(function(){
var td = $(this);
if(tdtext.txt == ''){
tdtext.txt = td.text();
tdtext.obj = td;
}else if(tdtext.txt == td.text()){
tdtext.count +=1;
td.hide();
td.addClass('todelete');
}else{
//before to change
tdtext.obj.attr('colspan',tdtext.count);
//
tdtext = {"obj":td,"txt":td.text(),"count":1};
}
});
if(tdtext.count > 1){
tdtext.obj.attr('colspan',tdtext.count);
}
$('.todelete').remove();
});
},
init(){
mapTable._tr();
mapTable._td();
}
}
I am attempting to create a string that contains all of the data within an HTML table using JavaScript (open to changing to JQuery). By using this method below, I receive an NaN value, instead of the data (numbers).
function Ard() {
var table = document.getElementById("tblData");
var dataStr = "";
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
var toAdd = col;
dataStr += toAdd;
}
}
};
I have also tried a jQuery method but it only returned an HTML object. It should be noted that when printing the 'col' value to the console, the data is collected properly (actual values).
The table I'm using is editable by the user, but it saves as a standard HTML table. Here is the basic code for the table below if it helps solve the problem.
<table id="tblData" class="table table-hover">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Treatment Number</th>
<th>Cell Number</th>
<th>Waste Container Number</th>
</tr>
</thead>
<tbody></tbody>
</table>
Any ideas towards how to get the innerHTML and add it properly to the string?
I would also like to do this with a row by column loop (set of two for or each loops maybe?) so that I know what column I'm grabbing from.
Since you are OK to use jquery,
var dataStr = "";
$('#tblData > tbody').each(function(e) {
dataStr += $(this).text();
});
console.log(dataStr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tblData" class="table table-hover">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Treatment Number</th>
<th>Cell Number</th>
<th>Waste Container Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>10101</td>
<td>20202</td>
<td>30303</td>
<td>40404</td>
<td>50505</td>
</tr>
<tr>
<td>wowowo</td>
<td>sksksk</td>
<td>alalal</td>
<td>qpqpqp</td>
<td>zmzmzm</td>
</tr>
</tbody>
</table>
If you want the dataStr to have the <td> tags also, you should use,
dataStr += $(this).html()
EDIT
If you also want to access the current column index, you can use this. But here, the dataStr would finally contain a single line string concatenating all the texts inside <td> tags.
$('#tblData > tbody > tr > td').each(function(e) {
var currentColNo = $(this).index();
dataStr += $(this).html();
});
With jQuery you could select all rows and the iterate over them and get the text:
var str = "", values = [];
$("#tblData").find('tbody').find('tr').each(function() {
//You can concatenate a string or push the values to an array
str += $(this).text();
values.push($(this).text());
});
console.log(str, values);
You can do it with pure js:
function Ard() {
var table = document.querySelectorAll("#tblData tr th");
var dataStr = "";
for (var i = 0; i < table.length; i++) {
dataStr += table[i].innerHTML;
}
};
JSFiddle Demo
This will get you all text from the table <td>s and post it into a textarea (just for demonstration purposes):
$('#out').val($('#tblData td').text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tblData" class="table table-hover">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Treatment Number</th>
<th>Cell Number</th>
<th>Waste Container Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>some</td><td>extra</td><td>data</td>
</tr>
</tbody>
</table>
<textarea id="out" rows=10 cols=60></textarea>
Update:
If you "just" want to put the <td> contents into a single variable you could do:
var str=$('#tblData td').text()
I extended your example so you will actually get a result.