Copy ( to clipboard ) only one required column contents of html data table - javascript

My requirement is simple.
I have a table with four columns. Have some mobile numbers in 2nd column "Mobile No.". I just want to copy ( to clipboard ) All the mobile numbers in the "Mobile No." column on button click.
Tried some javascript samples for the same, not worked as required. Please give some suggestions.
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<h2>HTML Table</h2>
<button id="copy-table-button" data-clipboard-target="#datatable"> Copy Mobile No. </button>
<table id="myTable">
<thead>
<tr>
<th>Sl No</th>
<th>Mobile No.</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1234567890</td>
<td>Maria</td>
<td>Active</td>
</tr>
<tr>
<td>2</td>
<td>2223330</td>
<td>Ruma</td>
<td>Active</td>
</tr>
<tr>
<td>3</td>
<td>3334440</td>
<td>Kumar</td>
<td>Not-Active</td>
</tr>
<tr>
<td>4</td>
<td>44455500</td>
<td>Subba</td>
<td>Active</td>
</tr>
<tr>
<td>5</td>
<td>555666111</td>
<td>Orayyo</td>
<td>Not-Active</td>
</tr>
<tr>
<td>6</td>
<td>555666111</td>
<td>Orayyo</td>
<td>Active</td>
</tr>
<tr>
<td>7</td>
<td>555666111</td>
<td>Orayyo</td>
<td>Not-Active</td>
</tr>
</tbody>
</table>
</body>
</html>
I just need to copy them as plain text, to paste in other websites or forms.
Should paste like this after copy..
1234567890
2223330
3334440
44455500
555666111
555666111
555666111
Thanks in advance.

This works for me, let me know if you have any troubles with it:
const copyButton = document.querySelector('#copy-table-button');
const copyToClipboard = (_) => {
const dataElements = document.querySelectorAll('tr > td:first-child + td');
const data = Array.from(dataElements).map(element => element.textContent).join('\n');
const blob = new Blob([data], {type: 'text/plain'});
const clipboardItem = new ClipboardItem({'text/plain': blob});
navigator.clipboard.write([clipboardItem]);
}
copyButton.addEventListener('click', copyToClipboard);

Related

How To Apply jquery filtering on click of html link

I have applied jQuery filters on a table with few hundreds rows and it works fine.
But I want to make few HTML links on top of table so users can click on that link to apply filter (instead of typing) for instance. List all record with city name Washington, something like that:
Desired Filtering
List all records with city name Washington
Here is the code:
$(document).ready(function() {
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<h2>Desired Filtering</h2>
<h3>List all records with city name Washington</h3>
<hr />
<h2>Working Filterable Table</h2>
<p>Type something in the input field to search the table for first names, last names or emails:</p>
<input id="myInput" type="text" placeholder="Search..">
<br><br>
<table>
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>City</th>
</tr>
</thead>
<tbody id="myTable">
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
<td>New York</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#mail.com</td>
<td>Washington</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#greatstuff.com</td>
<td>New York</td>
</tr>
<tr>
<td>Anja</td>
<td>Ravendale</td>
<td>a_r#test.com</td>
<td>New York</td>
</tr>
<tr>
<td>Mathew</td>
<td>Stars</td>
<td>a_z#test.com</td>
<td>Washintgon</td>
</tr>
</tbody>
</table>
so users can click on that link to apply filter (instead of typing)
You can store the filter that you want in the link using a data- attribute, then apply that to the search input using .val().
List all records with city name Washington
$(".addfilter").click(function() {
var filter = $(this).data("filter");
$("#myInput").val(filter);
$("#myInput").trigger("keyup");
return false;
});
Here I've given the link a class addfilter so that you can add new links without needing to change the code. The .click handler has return false; (or could use .preventDefault to stop the <a> from navigating away (the href='#' also stops the <a> from changing the whole page).
Updated snippet:
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
$(".addfilter").click(function() {
var filter = $(this).data("filter");
$("#myInput").val(filter);
$("#myInput").trigger("keyup");
return false;
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<h2>Desired Filtering</h2>
<h3>
List all records with city name Washington
<br/>
List all records with city name New York</h3>
<hr />
<h2>Working Filterable Table</h2>
<p>Type something in the input field to search the table for first names, last names or emails:</p>
<input id="myInput" type="text" placeholder="Search..">
<br><br>
<table>
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>City</th>
</tr>
</thead>
<tbody id="myTable">
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
<td>New York</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#mail.com</td>
<td>Washington</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#greatstuff.com</td>
<td>New York</td>
</tr>
<tr>
<td>Anja</td>
<td>Ravendale</td>
<td>a_r#test.com</td>
<td>New York</td>
</tr>
<tr>
<td>Mathew</td>
<td>Stars</td>
<td>a_z#test.com</td>
<td>Washintgon</td>
</tr>
</tbody>
</table>
For the above, in order to "apply" the filter, I've used .trigger("keyup") which calls your existing code. This is to keep the number of changes to a minimum; in practice you would want to pull this out into its own function. You also might like to use input instead of keyup as it will catch mouse-paste etc, giving something like:
function applyFilter(value) {
value = value.toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
}
$(".addfilter").click(function() {
var filter = $(this).data("filter");
$("#myInput").val(filter);
applyFilter(filter);
return false;
});
$("#myInput").on("input", function() {
var value = $(this).val();
applyFilter(value);
});

Mechanism binding click event handler to massive <td> elements

I'm writing a big HTML table which has same-data-coloring feature by user's double-clicking on a certain cell, the table has over 8000 cells and cells will be increased.
At this point, I thought it could be a burdened working to a web-browser.
Yes, I want to know the in-depth mechanism and burdening degree of attaching event-handler to massive <td> elements.
The code:
<script>
var otable = document.getElementById("htbl_drawresult");
var irIndex = 0;
var icIndex = 0;
var sintxt = "";
for(var i = 1; i < otable.rows.length; i++)
{
for(var j = 0; j < otable.rows[i].cells.length; j++)
{
otable.rows[i].cells[j].ondblclick = function()
{
irIndex = this.parentElement.rowIndex;
icIndex = this.cellIndex+1;
sintxt = this.innerText;
f_colorcell(sintxt, otable);
};
}
}
function f_colorcell(stxt, otbl){
var irow = otbl.rows.length;
var icol = otbl.rows[1].cells.length;
var i,j=0;
for(i=1; i<irow; i++)
{
for(j=0; j<icol; j++)
{
if (otbl.rows[i].cells[j].innerText == stxt){
otbl.rows[i].cells[j].style.background=\"red\";
}
}
}
}
</script>
Just summarising #C.RaysOfTheSun's answer:
Yes, it would be burdensome to attach an event each on every cell of the table.
However, you could structure your HTML in such a way that the cells (TDs) can each be uniquely identified. And when events propagate from a target to an ancestor (TABLE element for instance) where a listener is *commonly* attached, it's simple to determine the actual target in the listener.
document.addEventListener("DOMContentLoaded", main, false);
function main() {
var table = document.getElementsByTagName("TABLE")[0];
table.addEventListener("dblclick", handleDoubleClickOnTable, false);
}
function handleDoubleClickOnTable( /* event => */ e) {
var target = e.target;
var row, column;
var rowNumber, columnNumber;
if ("TD" !== target.tagName) {
return;
}
row = target.parentNode;
column = target;
rowNumber = row.dataset.rowNumber;
columnNumber = column.dataset.columnNumber;
alert(`You clicked on ( row[ ${ rowNumber } ], column[ ${ columnNumber } ] )`);
}
* {
font-family: monospace;
box-sizing: border-box;
}
table {
width: 100%;
margin-bottom: 1rem;
background-color: transparent;
border-collapse: collapse;
}
td {
vertical-align: bottom;
border-bottom: 2px solid #dee2e6;
border-top: 1px solid #dee2e6;
padding: 2rem;
}
<!-- Sample 3 x 3 table -->
<table>
<tr data-row-number="1">
<td data-column-number="1">( 1, 1 )</td>
<td data-column-number="2">( 1, 2 )</td>
<td data-column-number="3">( 1, 3 )</td>
</tr>
<tr data-row-number="2">
<td data-column-number="1">( 2, 1 )</td>
<td data-column-number="2">( 2, 2 )</td>
<td data-column-number="3">( 2, 3 )</td>
</tr>
<tr data-row-number="3">
<td data-column-number="1">( 3, 1 )</td>
<td data-column-number="2">( 3, 2 )</td>
<td data-column-number="3">( 3, 3 )</td>
</tr>
</table>
If you're talking about assigning an event handler for the cells (<td>) inside your table, you can do it in two ways:
1. Event Propagation
A shorter and much simpler way of doing it. You can assign an event handler to the parent (the <table> element itself) and everything inside it will have the event handler as well. Simply put, what the parent gets, the child will also get.
Recommended if you don't need a specific thing to happen when a given element is clicked. Although, you can always narrow things down by utilizing Event.Target.
In the example below, I have assigned a click event listener to the table (parent) so that when you click on anything inside it, an alert saying "You clicked on a cell and it had the value of [cell value]" will show up
Here's a working example for event propagation.
window.onload = ()=>{
// get our table
let tb = document.getElementById('main-table');
// assign a click event to it
tb.addEventListener('click', (e)=>{
alert(`You clciked on a cell and it had the value of ${e.target.innerHTML}`)
})
}
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<table class="table" id="main-table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
</tbody>
</table>
2. Manually assigning a specific event handler to each element
You can always set an event handler for each cell (<td>) specifically by grabbing them using JavaScript's built-in functions (i.e. querySelector, querySelectorAll, getElementById, etc...) then assigning a function to be called on a specific event using addEventListener
Not recommended for a large collection of elements.
You can play around with the snippet below here :)
window.onload = ()=>{
// get our table
let table = document.getElementById('main-table');
// get all the cells in the table element above
let tableCells = table.querySelectorAll('td');
// assign an event listener to each cell <td> element inside that table specifically
for(let i = 0; i < tableCells.length; i++){
tableCells[i].addEventListener('click', function(e){
alert(`You clicked on cell index ${i} and it had the value of ${this.innerHTML}`);
})
}
}
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<table class="table" id="main-table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
</tbody>
</table>
:)
If you want to add click event listeners, you can use jQuery. You can use this for any HTML element.
$("#button").click(function() {
$("#result").css("background-color", "yellow");
});
$("#button").dblclick(function() {
$("#result").css("background-color", "red");
});
body {
font-family: Arial, sans-serif;
}
td {
width: 20px;
height: 20px;
text-align: center;
margin: 0;
border: .5px solid black;
}
#button {
background-color: white;
}
#result {
background-color: blue;
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you click the <code>div</code> once, the square will turn yellow.<br>
If you double click the <code>div</code>, the square will turn red.<br>
CM = Click Me
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>7</td>
<td id="button">CM</td>
<td>9</td>
<td>10</td>
</tr>
<tr>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
<td>15</td>
</tr>
<tr>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
</tr>
</table>
<div id="result"></div>

Loop HTML table and add the identical items and its calculated amount to another table

<html>
<body>
<div>
<table border="1" id="topTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="topTableBody">
<tr>
<td>Apples</td>
<td>50</td>
</tr>
<tr>
<td>Apples</td>
<td>25</td>
</tr>
<tr>
<td>Oranges</td>
<td>30</td>
</tr>
<tr>
<td>Strawberry</td>
<td>60</td>
</tr>
<tr>
<td>Cherry</td>
<td>10</td>
</tr>
<tr>
<td>Guava</td>
<td>5</td>
</tr>
<tr>
<td>Strawberry</td>
<td>20</td>
</tr>
</tbody>
</table>
</div>
<button id="btn">Click</button>
</br>
<div>
<table border="1" id="bottomTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="bottomTableBody">
</tbody>
</table>
</div>
</body>
</html>
When I press on the button I want it to loop through the top table and get the item names that're alike and add them in one row with the sold amount combined in the bottom table ex: apples will have their own row with a sold amount of 75 and others who have no names that're alike will have their own row such as Oranges with the sold amount also.
If you can use JQuery.
(JSFiddle: http://jsfiddle.net/inanda/o9axgkaz/):
jQuery('#btn').on('click', function() {
var sumMap = {};
//Iterate through table rows
$("table tbody tr").each(function () {
if (sumMap[$(this).children('td:nth-child(1)').text()]) {
sumMap[$(this).children('td:nth-child(1)').text()] = sumMap[$(this).children('td:nth-child(1)').text()] +Number($(this).children('td:nth-child(2)').text());
} else {
sumMap[$(this).children('td:nth-child(1)').text()] = Number($(this).children('td:nth-child(2)').text());
}
})
//Append result to the other table
$.each(sumMap, function (i, val) {
$('#bottomTable tr:last').after('<tr><td>'+i+'</td><td>'+val+'</td>');
});
});
Pure javascript:
(JSFiddle: http://jsfiddle.net/inanda/2dmwudfj/ ):
appendResultToBottomTable= function() {
var sumMap = calculate();
appendResultToTable('bottomTableBody', sumMap);
}
function calculate() {
var table = document.getElementById("topTableBody");
var map = {};
for (var i = 0, row; row = table.rows[i]; i++) {
var itemType=(row.cells[0].innerText || row.cells[0].textContent);
var value=(row.cells[1].innerText || row.cells[1].textContent);
if (map[itemType]) {
map[itemType] = map[itemType] +Number(value);
} else {
map[itemType] = Number(value);
}
}
return map;
}
function appendResultToTable(tableId, sumMap){
var table = document.getElementById(tableId);
for (var item in sumMap){
var row = table.insertRow(table.rows.length);
var cellItem = row.insertCell(0);
var cellValue = row.insertCell(1);
cellItem.appendChild(document.createTextNode(item));
cellValue.appendChild(document.createTextNode(sumMap[item]));
}
}
If it is applicable for your project to use external libraries, you can do it with code like below:
alasql('SELECT Item,SUM(CONVERT(INT,Sold)) AS Sold \
INTO HTML("#res",{headers:true}) \
FROM HTML("#topTable",{headers:true}) \
GROUP BY Item');
Here:
SELECT Item, SUM(Sold) FROM data GROUP BY Item is a regular SQL expression to group and sum data from the table
CONVERT(INT,Sold) conversion procedure from string to INT type
FROM HTML() and INTO HTML() special functions to read/write data from/to HTML table, {headers:true} is a parameter to use headers
I added some minor CSS code (for table and cells borders), because Alasql generates the "plain" HTML table.
See the working snippet below.
(Disclaimer: I am an author of Alasql library)
function run() {
alasql('SELECT Item,SUM(CONVERT(INT,Sold)) AS Sold INTO HTML("#res",{headers:true}) FROM HTML("#topTable",{headers:true}) GROUP BY Item');
}
#res table {
border:1px solid black;
}
#res table td, th{
border:1px solid black;
}
<script src="http://alasql.org/console/alasql.min.js"> </script>
<div>
<table border="1" id="topTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="topTableBody">
<tr>
<td>Apples</td>
<td>50</td>
</tr>
<tr>
<td>Apples</td>
<td>25</td>
</tr>
<tr>
<td>Oranges</td>
<td>30</td>
</tr>
<tr>
<td>Strawberry</td>
<td>60</td>
</tr>
<tr>
<td>Cherry</td>
<td>10</td>
</tr>
<tr>
<td>Guava</td>
<td>5</td>
</tr>
<tr>
<td>Strawberry</td>
<td>20</td>
</tr>
</tbody>
</table>
</div>
<button id="btn" onclick="run()">Click</button>
</br>
<div id="res"></div>

Highlight cells with past dates

Hi guys I dont know if this is something that a new programmer should true or not, but heres my problem. I have a table of 13 columns at at present about 400 rows. yes i nkow this is a large table and unfortunatley it will only be getting bigger. what i am trying to achive with this table, somehow, is to have a function that checks the cell contents ( a date dd/mm/yyyy) in the 12th coloumn and if the date has past that it will will add a css to the row.
Through help from some very intelligent programmers i have a code that should work. but i cant get it to work in any way.
Can anyone help me out with this problem.
Thanks.
The code that i have is:
<script language="javascript">
$(document).ready(function() {
function parseDate(dateString)
{
return new Date(Date.parse(dateString));
}
$('#names tr').each(function(index)
{
var row = $(this);
if (parseDate(elem.find("td:eq(1)").text()) < new Date())
row.addClass('row');
});
});
</script>
My table is set out like this:
<tr>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>data</td>
<td>Date</td>
<td>Date</td>
<td>Data</td>
</tr>
ok and this is what i have now:
<html>
<head>
<style>
#sprog tr {
background: #00FF00;
}
#sprog tr.past {
background: #FF0000;
}
</style>
<script src="jquery 1.4.2.js"></script>
<script>
$(function()
{
$('#sprog .date').each(function()
{
var row_date = Date.parse($(this).text().replace(/(\d{2})\/(\d{2})\/(\d{4})/, '$2/$1/$3'));
var now_date = new Date().getTime();
if(row_date < now_date)
{
$(this).parent('tr').addClass('past');
}
}
);
}
);
</script>
<title>cells</title>
</head>
<body>
<table id="sprog">
<tbody>
<tr>
<td>14/08/2010</td>
<td>20/10/2015</td>
</tr>
<tr>
<td>2</td>
<td class="date">14/10/2010</td>
</tr>
<tr>
<td>3</td>
<td class="date">04/10/2010</td>
</tr>
<tr>
<td>10/12/2010</td>
<td class="date">12/10/2010</td>
</tr>
<tr>
<td>12/10/2010</td>
<td class="date">01/01/1900</td>
</tr>
</tbody>
</table>
</body>
</html>
HTML:
<table id="dates_table">
<tr>
<th>Name</th>
<th>Date of Birth</th>
</tr>
<tr>
<td>Bob</td>
<td class="date">01/02/2003</td>
</tr>
<tr>
<td>Johnny</td>
<td class="date">03/02/1980</td>
</tr>
<tr>
<td>Ted</td>
<td class="date">14/12/2010</td>
</tr>
<tr>
<td>Jane</td>
<td class="date">08/08/2005</td>
</tr>
</table>​
CSS:
#dates_table tr {
background: #00FF00;
}
#dates_table tr.past {
background: #FF0000;
}​
JavaScript:
$(function()
{
$('#dates_table .date').each(function()
{
var row_date = Date.parse($(this).text().replace(/(\d{2})\/(\d{2})\/(\d{4})/, '$2/$1/$3'));
var now_date = new Date().getTime();
if(row_date < now_date)
{
$(this).parent('tr').addClass('past');
}
}
);
}
);​
Note I've added a class="date" to the date <td>s so position won't make a difference.
Live demo here: http://jsfiddle.net/LPjfS/2/
Pure javascript should work:
var theTable = $('yourTable').tBodies[0];
for(x=0;x<theTable.rows.length;x++) {
if(theTable.rows[x].cells[11]=='foo') {
theTable.rows[x].cells[11].style.whatever= 'bar';
}
}
Code is untested - sorry - but should be pretty good.
A good explanation: http://www.howtocreate.co.uk/tutorials/javascript/domtables
Ok so after some digging i found that i wasn't calling the jquery correctly and i should actually look like this:
<html>
<head>
<title>trial cell highlight</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<style type="text/css">
body {
background-color: transparent;
padding: 10px;
}
#demotable1 tr {
background: white;
}
#demotable1 tr.past {
background: #FF0000;
color: #999999;
}
</style>
<script type="text/javascript">
//<![CDATA[
$(function()
{
$('#demotable1 .date').each(function()
{
var cell_date = Date.parse($(this).text().replace(/(\d{2})\/(\d{2})\/(\d{4})/, '$2/$1/$3'));
var now_date = new Date().getTime();
if(cell_date < now_date)
{
$(this).parent('tr').addClass('past')
}
}
);
}
);
//]]>
</script>
</head>
<body>
<table id="demotable1">
<tbody>
<tr>
<th>Name</th>
<th>Date of Birth</th>
</tr>
<tr>
<td>Bob</td>
<td class="date">01/02/2003</td>
</tr>
<tr>
<td>Johnny</td>
<td class="date">03/02/1980</td>
</tr>
<tr>
<td>Ted</td>
<td class="date">14/12/2010</td>
</tr>
<tr>
<td>Jane</td>
<td class="date">08/08/2005</td>
</tr>
</tbody>
</table>
</body>
</html>
Thanks to every one who helped me out with this one.

What is a good solution for cross browser javascript redirect with history?

I am currently fighting Google Chrome on the following action:
location.href = url
location.replace(url)
document.location = url
window.navigate(url) // doesn't work in Chrome/Firefox
location.assign(url)
window.open(url, '_self')
window.location.href = url
I have tried all, and neither will add a history entry. Is there a way in Google Chrome to do a javascript redirect WITH history?
Thanks.
Explanation
We have a table of items, when clicking on the row, I want the page to navigate to a specified URL, if anyone has a good solution to this other than using the onclick=send method we are using now, please let me know.
Update
It appears that Stackoverflow its-self has this exact same issue. In the main view, click on one of the first 3 columns in the question list (# answers, etc..), then click the back button, it will take you back 2 pages.
Although, I first must say that this is Chrome behaving stupid, and you probably should not worry about it. Try to create a dummy form and with a GET method and programmatically submit it...
<form id="dummyForm" method="GET" action="#">
<input type="hidden" name="test" value="test" />
</form>
Then your onclick...
var frm = document.forms["dummyForm"];
frm.action = url;
frm.submit();
all javascript solution based on #Josh Stodola answer
function goTo(url, data){
var ele_form = document.createElement("FORM");
ele_form.method = "POST";
ele_form.id = 'dummy_form';
ele_form.action = url;
if (!!data){
for(key in data){
var dummy_ele = document.createElement('INPUT');
dummy_ele.name = key;
dummy_ele.value = data[key];
dummy_ele.type = 'hidden';
ele_form.appendChild(dummy_ele);
}
}
document.getElementsByTagName('body')[0].append(ele_form);
document.getElementById('dummy_form').submit();
}
I know this is an older question, but if you're navigating to a link on the same page, you should be able to simply do the following, where 123 is the item id:
window.location = "items/123";
What you could do using jQuery is something like:
$("table tbody td").wrapInner('');
Since I don't know the structure of your markup it's difficult to provide a more specific fix.
See the jQuery documentation on wrapInner.
What about "clicking" a link with JS?
blah blah
<script type="text/javascript">
$(document).ready(function() {
$('#clickme').click();
});
</script>
I'm not sure if this work, but it should mimic a user clicking the link.
Taking what Josh Stodola recommended, and doing it with jquery instead, I have created a method that seems to get around this Chrome issue without a lot of overhead in the markup.
Here is a fully working version.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Row Navigation with History</title>
<style type="text/css">
body {
font: 14px Georgia, serif;
}
#page-wrap {
width: 800px;
margin: 0 auto;
}
table {
border-collapse:collapse;
width:100%;
}
thead {
text-align:left;
font: 16px serif;
}
tbody {
font: 14px Georgia, serif;
}
tr {
cursor:pointer;
}
td {
border: 1px solid #ccc;
padding:10px;
}
.slim {
width:88px;
}
.wide {
width:300px;
}
.hover {
background-color:#eee;
}
</style>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
</script>
<script type="text/javascript">
$(function() {
$("td").hover(function() {
$(this).parent().addClass("hover");
}, function() {
$(this).parent().removeClass("hover");
});
$("tr").click(function() {
if (navigator.userAgent.toString().indexOf("Chrome/2") != -1)
{
var form = $("<form></form>");
form.attr("method", "get");
form.attr("action", $(this).attr("rel"));
form.submit();
} else {
location.href = $(this).attr("rel");
}
});
});
</script>
</head>
<body>
<div id="page-wrap">
<table>
<colgroup />
<colgroup class="wide" />
<colgroup class="slim" />
<colgroup class="slim" />
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr rel="http://stackoverflow.com/questions/1173912/what-is-a-good-solution-for-cross-browser-javascript-redirect-with-history">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
<tr rel="http://www.stackoverflow.com">
<td>Title</td>
<td>Description</td>
<td>1/1/2009</td>
<td>Available</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
chrome is not supported location.reload. Use window.open(url, '_self') for page redirect
Here is a nice functional and clean jQuery solution based on Josh Stodola's (which didn't work for me).
function redirect(url, data) {
var form = $('<form method="get"></form>');
form.attr("action", url);
for (key in data){
var input = $('<input type="hidden"/>');
input.attr("name", key);
input.attr("value", data[key]);
form.append(input);
}
$("body").append(form);
$(form)[0].submit();
}

Categories

Resources