I have the following HTML table:
<table border="1">
<tr>
<td>blue</td>
</tr>
<tr>
<td>red</td>
</tr>
<tr>
<td>black</td>
</tr>
</table>
I would like each row in this table have a number automatically assigned to each item.
How could he do?
The following CSS enumerates table rows (demo):
table {
counter-reset: rowNumber;
}
table tr::before {
display: table-cell;
counter-increment: rowNumber;
content: counter(rowNumber) ".";
padding-right: 0.3em;
text-align: right;
}
<table cellpadding="0">
<tr><td>blue</td></tr>
<tr><td>red</td></tr>
<tr><td>yellow</td></tr>
<tr><td>green</td></tr>
<tr><td>purple</td></tr>
<tr><td>orange</td></tr>
<tr><td>maroon</td></tr>
<tr><td>mauve</td></tr>
<tr><td>lavender</td></tr>
<tr><td>pink</td></tr>
<tr><td>brown</td></tr>
</table>
If the CSS cannot be used, try the following JavaScript code (demo):
var table = document.getElementsByTagName('table')[0],
rows = table.getElementsByTagName('tr'),
text = 'textContent' in document ? 'textContent' : 'innerText';
for (var i = 0, len = rows.length; i < len; i++) {
rows[i].children[0][text] = i + ': ' + rows[i].children[0][text];
}
<table border="1">
<tr>
<td>blue</td>
</tr>
<tr>
<td>red</td>
</tr>
<tr>
<td>black</td>
</tr>
</table>
And if you would use headers as well the following is the thing you need:
http://jsfiddle.net/davidThomas/7RyGX/
table {
counter-reset: rowNumber;
}
table tr:not(:first-child) {
counter-increment: rowNumber;
}
table tr td:first-child::before {
content: counter(rowNumber);
min-width: 1em;
margin-right: 0.5em;
}
note the: ":not(:first-child)" in there.
Here is a modification of David Thomas' CSS solution that works with or without a header row in the table. It increments the counter on the first td cell of each row (thereby skipping the row with only th cells):
table
{
counter-reset: rowNumber;
}
table tr > td:first-child
{
counter-increment: rowNumber;
}
table tr td:first-child::before
{
content: counter(rowNumber);
min-width: 1em;
margin-right: 0.5em;
}
You can see the behavior in this jsfiddle.
Here's a javascript solution that will add a cell at the beginning of each row , this cell will be used for numbering, if there is a th cell this gets a colspan=2 attribute.
var addNumeration = function(cl){
var table = document.querySelector('table.' + cl)
var trs = table.querySelectorAll('tr')
var counter = 1
Array.prototype.forEach.call(trs, function(x,i){
var firstChild = x.children[0]
if (firstChild.tagName === 'TD') {
var cell = document.createElement('td')
cell.textContent = counter ++
x.insertBefore(cell,firstChild)
} else {
firstChild.setAttribute('colspan',2)
}
})
}
addNumeration("test")
<table class="test" border="1">
<tr>
<th>hi!</th>
</tr>
<tr>
<td>blue</td>
</tr>
<tr>
<td>red</td>
</tr>
<tr>
<td>black</td>
</tr>
</table>
Related
I am trying to grab the contents from one column only. but it's grabbing that one column as well as the rest of the row content and displaying it. How can I just grab only the age column?
document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('empTable');
// LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
for (i = 1; i < myTab.rows.length; i++) {
// GET THE CELLS COLLECTION OF THE CURRENT ROW.
var objCells = myTab.rows.item(i).cells;
// LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
for (var j = 2; j < objCells.length; j++) {
info.innerHTML = info.innerHTML + ' ' + objCells.item(j).innerHTML;
}
info.innerHTML = info.innerHTML + ',';
}
th,
td,
p,
input {
font: 14px Verdana;
}
table,
th,
td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight: bold;
}
<head>
<title>Read Data from HTML Table uisng JavaScript</title>
</head>
<body>
<table id="empTable">
<tr>
<th>ID</th>
<th>Employee Name</th>
<th>Age</th>
<th>Color</th>
</tr>
<tr>
<td>01</td>
<td>Alpha</td>
<td>37</td>
<td>Blue</td>
</tr>
<tr>
<td>02</td>
<td>Bravo</td>
<td>29</td>
<td>Red</td>
</tr>
</table>
<p id="info"></p>
Outcome:
37 Blue, 29 Red,
Desired outcome:
37, 29
Any help and explanation is greatly appreciated!
Thanks,
bfox
You're looping through all elements of objCells after index 2 which is returning objCells[2] (37) and objCells[3] (blue)
just access objCells[2] like so
for (var j = 2; j < objCells.length; j++) {
info.innerHTML = info.innerHTML + ' ' + objCells.item(j).innerHTML;
}
Should be
info.innerHTML = info.innerHTML + ' ' + objCells.item(2).innerHTML;
Instead of looping through all the cells of each row, you need to only process the 3rd cell of each row, here is an example:
var myTab = document.getElementById('empTable');
var ages = [];
for (i = 1; i < myTab.rows.length; i++) {
var currentRow = myTab.rows[i];
var ageCell = currentRow.cells[2];
ages.push(ageCell.textContent);
}
var info = document.getElementById('info');
info.innerHTML = ages.join();
th,
td,
p,
input {
font: 14px Verdana;
}
table,
th,
td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight: bold;
}
<head>
<title>Read Data from HTML Table uisng JavaScript</title>
</head>
<body>
<table id="empTable">
<tr>
<th>ID</th>
<th>Employee Name</th>
<th>Age</th>
<th>Color</th>
</tr>
<tr>
<td>01</td>
<td>Alpha</td>
<td>37</td>
<td>Blue</td>
</tr>
<tr>
<td>02</td>
<td>Bravo</td>
<td>29</td>
<td>Red</td>
</tr>
</table>
<p id="info"></p>
What this does is to loop through each row and add the 3rd cell's text content to the ages array, once all the rows are processed, the #info element's inner HTML is set to a string representation of the ages array (.join() just creates a string which contains the string representation of each element of the array separated by a comma).
In the above code, the second for-loop is reading all cells starting from index-2.
This is causing all the unnecessary values to get concatenated.
The problem can be fixed by replacing the for-loop with an assignment statement in an if-condition.
Additionally, the trailing comma can be avoided by using an array instead of updating the inner-html of the result element inside the loop.
Here is the working code with the suggested change:
<!DOCTYPE html>
<html>
<head>
<title>Read Data from HTML Table uisng JavaScript</title>
</head>
<body>
<table id="empTable">
<tr>
<th>ID</th>
<th>Employee Name</th>
<th>Age</th>
<th>Color</th>
</tr>
<tr>
<td>01</td>
<td>Alpha</td>
<td>37</td>
<td>Blue</td>
</tr>
<tr>
<td>02</td>
<td>Bravo</td>
<td>29</td>
<td>Red</td>
</tr>
</table>
<p id="info"></p>
<script>
document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('empTable');
// Declare a result array
var result = []
// LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
for (i = 1; i < myTab.rows.length; i++) {
// GET THE CELLS COLLECTION OF THE CURRENT ROW.
var objCells = myTab.rows.item(i).cells;
// Add the content of second cell to result array
if(objCells.length >= 2) {
result.push(objCells.item(2).innerHTML);
}
}
// Show the result array in the info element
document.getElementById('info').innerHTML = result
</script>
</body>
</html>
Output:
ID Employee Name Age Color
01 Alpha 37 Blue
02 Bravo 29 Red
37,29
Have been dabbling around with this piece of code, only I could do with some input. Could really do with a follow up working examples altered code snippet if at all possible. Need to figure the filter/search - returning results being limited to a specified table heading ('th/tr' - tags), namely the Title heading and search within ONLY this area, though displaying the whole cells still (Title, Description and Date).Any questions I'll be pleased to help.
var input, table, rows, noMatches, markInstance;
$(document).ready(function init() {
input = document.getElementById('myInput');
noMatches = document.getElementById('noMatches');
table = document.getElementById('myTable');
rows = table.querySelectorAll('tr');
markInstance = new Mark(table);
input.addEventListener('keyup', _.debounce(ContactsearchFX, 250));
});
function ContactsearchFX() {
resetContent();
markInstance.unmark({
done: highlightMatches
});
}
function resetContent() {
$('.noMatchErrorText').remove();
//Remove this line to have a log of searches
//noMatches.textContent = '';
rows.forEach(function(row) {
$(row).removeClass('show');
});
}
function highlightMatches() {
markInstance.mark(input.value, {
each: showRow,
noMatch: onNoMatches,
})
}
function showRow(element) {
//alert(element);
$(element).parents('tr').addClass('show');
$(element).parents('tr').siblings('tr').addClass('show');
//Parents incase of several nestings
}
function onNoMatches(text) {
$('#myInput').after('<p class="noMatchErrorText">No records match: "' + text + '"</p>');
}
.input-wrap {
margin-bottom: 12px;
}
#myInput:invalid~.hints {
display: block;
}
#noMatches:empty,
#noMatches:empty+.hints {
display: none;
}
.style1 tr {
display: none;
}
.style1 .show {
display: table-row;
}
mark {
background: orange;
font-weight: bold;
color: black;
}
.style1 {
text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.11/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js"></script>
<div class="input-wrap">
<label>
Search Titles:
<input id="myInput" type="text" required
placeholder="Search Titles" />
</label>
</div>
<div class="hintsWrap">
<p id="noMatches"></p>
<p class="hints">
Hints: type "Title1", "Title2", "Title3"...
</p>
</div>
<br />
<br />
<table id="myTable" style="width: 100%" class="style1">
<tr>
<td>
<br />
<br />
<br />
<table style="width: 100%">
<tr>
<th class="style1">Title</th>
<td>title1</td>
</tr>
<tr>
<th class="style1">Description</th>
<td>description1</td>
</tr>
<tr>
<th class="style1">Date</th>
<td>date1</td>
</tr>
</table>
<br />
<table style="width: 100%">
<tr>
<th class="style1">Title</th>
<td>title2</td>
</tr>
<tr>
<th class="style1">Description</th>
<td>description2</td>
</tr>
<tr>
<th class="style1">Date</th>
<td>date2</td>
</tr>
</table>
<br />
<br />
<table style="width: 100%">
<tr>
<th class="style1">Title</th>
<td>title3</td>
</tr>
<tr>
<th class="style1" style="height: 23px">Description</th>
<td style="height: 23px">description3</td>
</tr>
<tr>
<th class="style1">Date</th>
<td>date3</td>
</tr>
</table>
<br />
<br />
<table style="width: 100%">
<tr>
<td>
<table style="width: 100%">
<tr>
<th class="style1">Title</th>
<td>title4</td>
</tr>
<tr>
<th class="style1">Description</th>
<td>description4</td>
</tr>
<tr>
<th class="style1">Date</th>
<td>date4</td>
</tr>
</table>
</td>
</tr>
</table>
<br />
</td>
</tr>
</table>
As continuation from comments above, and since this was something basic that you would like to use, i posted it here.
I added some notes on the code but the essences are:
This is just a really basic approach without any use of libraries.
I play with classes in order to hide the table rows and also to mark the result
Although i leave the part on the script that display: none; the lines of the table, you can manipulate the CSS and delete it from the code.
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.querySelectorAll("tbody > tr");
for (i = 0; i < tr.length; i++) { // Loop through all table rows, and hide those who don't match the search query
td = tr[i].getElementsByTagName("td")[0]; // this will search on the Title col. You can change this to search on other cols.
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) { // found
tr[i].style.display = "";
tr[i].classList.add("mark"); // mark result
}
else { // didn't found
tr[i].style.display = "none";
tr[i].classList.remove("mark"); // unmark result
}
}
if (input.value === '') { // case the input is clear
tr[i].classList.remove("mark"); // unmark result
tr[i].style.display = "none";
}
}
}
table {position: relative; min-width: 320px;} /* */
tbody tr {opacity: 0;} /* this will hide the table's info + will show the result under the headers */
tr.mark {opacity: 1;} /* this will show the result row */
/* basic style (markers) to the result row - just for demonstration purpose */
tr.mark td {background: yellow;} /* (second) col */
tr.mark td:first-child {background: blue;} /* first col */
tr.mark td:last-child {background: orange;} /* third col*/
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search Titles..">
<table id="myTable">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>bla bla bla</td>
<td>description1</td>
<td>date1</td>
</tr>
<tr>
<td>yada yada yada</td>
<td>description2</td>
<td>date2</td>
</tr>
<tr>
<td>Another Title</td>
<td>description3</td>
<td>date3</td>
</tr>
</tbody>
</table>
Hope that it is what you searched for, and Enjoy code!
Solution 1. you can play with css selectors to achieve your goal:
#myTable table tr:first-child td mark {
background: orange;
font-weight: bold;
color: black;
}
mark {
background: initial;
}
Solution 2. edit your init function for sibling only titles like this:
$(document).ready(function init() {
input = document.getElementById('myInput');
noMatches = document.getElementById('noMatches');
/************************************************
NOTE :: your last table element doesn't match your template
************************************************/
table = document.querySelectorAll('#myTable table tr:first-child td');
rows = document.querySelectorAll('#myTable table tr');
markInstance = new Mark(table);
input.addEventListener('keyup', _.debounce(ContactsearchFX, 250));
});
Have fun
I know I can use the following code to remove rows in vanilla Javascript:
var table = document.getElementById('table');
function deleteRow () {
table.deleteRow(1);
};
table { background: #ccc; width: 100%; }
table thead { background: #333; color: #fff; }
table tbody { background: magenta; color: #fff; }
<button onclick="deleteRow()">Delete Row</button>
<table id="table">
<thead>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
</thead>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
</table>
But this code leaves an empty tbody tag behing. JS has methods for removing thead and tfoot elements, but it seems it's missing a deleteTbody one.
How am I supposed to remove a tbody and all it's contents by using pure javascript only? No jQuery, please!
Try using:
var tbl = document.getElementById("table"); // Get the table
tbl.removeChild(tbl.getElementsByTagName("tbody")[0]); // Remove first instance of body
https://jsfiddle.net/Ltdr2qv4/1/
Use querySelectorAll() to iterate through all TBODY elements, then remove those that have no children:
var table = document.getElementById('table');
function deleteRow() {
table.deleteRow(1);
var tb = document.querySelectorAll('tbody');
for (var i = 0; i < tb.length; i++) {
if (tb[i].children.length === 0) {
tb[i].parentNode.removeChild(tb[i]);
}
}
};
table {
background: #ccc;
width: 100%;
}
table thead {
background: #333;
color: #fff;
}
table tbody {
background: magenta;
color: #fff;
}
<button onclick="deleteRow()">Delete Row</button>
<table id="table">
<thead>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
</thead>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
</table>
If you want to remove the tbody tag, you could select the row itself rather than the table, then use the removeChild function.
var table = document.getElementById('table');
var row = document.getElementsByTagName('tbody')[0];
function deleteRow () {
row.parentNode.removeChild(row);
};
There is no deleteTbody but there is removeChild:
var parent = document.getElementById("parent-id");
var child = document.getElementById("child-id");
parent.removeChild(child);
I hope it will help you. I am sorry. It is too late to answer.
tbody-data is tbody's id value.
$("#tbody-data tr").remove();
I built an table using JavaScript. However when I try to call jQuery on that table it doesnt work. I am trying to make jQuery highlight the columns of the table when I hoover with it.
Here is my code
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(tableRef.rows.length);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell
var newText = document.createTextNode('New row')
// Append a text node to the cell
newCell.appendChild(newText);
//Apend new cell to same row
var newCell = newRow.insertCell(1);
var newText = document.createTextNode('Nea')
newCell.appendChild(newText);
//highlight column
$('td').on('mouseenter', function() {
var i = $(this).parent().children().index(this);
$('col').removeClass('hovered');
$('col:nth-child(' + (i + 1) + ')').addClass('hovered');
});
$('td').on('mouseleave', function() {
$('col').removeClass('hovered');
});
table {
border-collapse: collapse;
}
table tr:hover {
background-color: grey;
}
col.hovered {
background-color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>aaaaa</td>
<td>aaaaa</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
</tfoot>
</table>
Here is JsFiddle
http://jsfiddle.net/4sR2G/764/
I managed to get the effect using
<colgroup>
<col></col>
<col></col>
<col></col>
</colgroup>
From one of the examples you gave.
Sample table
<table>
<tr>
<td>Age</td>
<td>12</td>
<td>Gender</td>
<td>Male</td>
<td>Some long label</td>
<td>Some long label value</td>
...
...
could be more...
</tr>
</table>
Without the width:100% content should fit to each column container but I would like to make the table expand across the whole page. Setting table width: 100% equally distributes the column. I would like to make each label (Labels: Age, Gender, Some long label) fit it's column container and the rest equally divided among themselves (Values: 12, Male, Some long label value).
I know setting <td width="5%">Age</td> or setting it in css should do the job but I think this is counter productive especially if you have to do that with a lot of columns.
Is there a way to accomplish this in css with lesser code, javascript or jquery maybe? Any hint or direction on how this can be done?
Note:
I've read this but I would like to avoid injecting width="%" inside html.
May be colgroup can help you out. Try this
The HTML is:
<table border = "1" cellspacing = "0" cellpadding = "0">
<colgroup>
<col>
<col style="width:40%">
<col>
<col style="width:40%">
</colgroup>
<tr>
<td>Age</td>
<td>12</td>
<td>Gender</td>
<td>Male</td>
</tr>
</table>
If I understand you correctly, this is what you’re looking for:
table { width: 100% }
td:nth-child(odd) { width: 5% }
or if you want the content to be “hugged” by a cell:
table { width: 100% }
td:nth-child(odd) { width: 1%; white-space: nowrap }
$(function(){
$(window).load(function() {
updateCellWidth()
})
$(window).resize(function() {
updateCellWidth()
})
})
function updateCellWidth() {
var width = 0, cols = 0
$("table td:nth-child(even)").each(function(){
++cols
width += $(this).width()
})
if (cols > 0) {
var evenCellWidth=($("table").width()-width)/cols
$("table td:nth-child(even)").css("width", evenCellWidth + "px")
}
}
Are you looking for something like this.?
Then border-collapse, cellspacing & cellpadding might help you.
This is what I came up with. Thanks for the ideas.
<style type="text/css">
table {
border-collapse: collapse;
width: 100%;
}
table td {
border: 1px solid #000;
white-space: nowrap;
}
</style>
<body>
<table id="tbl1">
<tr>
<td>Age</td>
<td>12</td>
<td>Gender</td>
<td>Male</td>
<td>Some Long Label</td>
<td>Some Long Label Value</td>
</tr>
</table>
<script type="text/javascript">
var tbl = document.getElementById('tbl1');
var rowCount = tbl.rows.length;
var colCount = tbl.rows[0].cells.length;
for (var i = 0 ; i < colCount; i++) {
if (i%2 == 0) {
tbl.rows[0].cells[i].style.width = tbl.rows[0].cells[i].innerHTML.length + 'px';
}
}
</script>