How to add hyperlink to table row <tr> - javascript

I am having a table with its table row <tr> generating in a loop to form multiple rows.
I want to give separate <a> link to each <tr>. Since in table we can add only add data to <td> only, I am not able to achieve that.
Is there any other way to achieve this?

Html:
<table>
<tr href="http://myspace.com">
<td>MySpace</td>
</tr>
<tr href="http://apple.com">
<td>Apple</td>
</tr>
<tr href="http://google.com">
<td>Google</td>
</tr>
</table>
JavaScript using jQuery Library:
$(document).ready(function(){
$('table tr').click(function(){
window.location = $(this).attr('href');
return false;
});
});
You can try this here: http://jsbin.com/ikada3
CSS (optional):
table tr {
cursor: pointer;
}
OR the HTML valid version with data-href instead of href:
<table>
<tr data-href="http://myspace.com">
<td>MySpace</td>
</tr>
<tr data-href="http://apple.com">
<td>Apple</td>
</tr>
<tr data-href="http://google.com">
<td>Google</td>
</tr>
</table>
JS:
$(document).ready(function(){
$('table tr').click(function(){
window.location = $(this).data('href');
return false;
});
});
CSS:
table tr[data-href] {
cursor: pointer;
}

Playing off of #ahmet2016 and keeping it W3C standard.
HTML:
<tr data-href='LINK GOES HERE'>
<td>HappyDays.com</td>
</tr>
CSS:
*[data-href] {
cursor: pointer;
}
jQuery:
$(function(){
$('*[data-href]').click(function(){
window.location = $(this).data('href');
return false;
});
});

The easiest way I've found to turn a table row into a link is to use the onclick attribute with window.location.
<table>
<tr onclick="window.location='/just/a/link.html'">
<td></td>
</tr>
</table>

I agree with the first response, more information is needed. But if you're just trying to make a table of links, you can just do
<tr><td>...</td></tr>

If you're saying that you want to make each <tr> clickable, you can add a click event to each <tr>, or better yet, add a .delegate() handler to the table that manages clicks on its <tr> elements.
$('#myTable').delegate('tr','click',function() {
alert( 'i was clicked' );
});
This code assumes your table has the myTable ID:
<table id="myTable">
<tr><td> cell </td></tr>
<tr><td> cell </td></tr>
</table>
If this isn't what you meant, then please clarify your question, and post the relevant javascript code you're using.

PHP:
echo "<tr onclick=\"window.location='".$links[$i]."'\">......";
Javascript without jQuery:
x=1;
.
.
for (...) {
var tr=document.createElement('tr');
tr.onclick=function() { window.location='page'+(x++)+'.html'}
tr.style.cursor='pointer';
.
}
will let the user click on each row
you can use an array to load the pages too:
x=0;
var pages=["pagea.html","pageb.html"]
.
.
for (...) {
var tr=document.createElement('tr');
tr.onclick=function() { window.location=page[x++];}
tr.style.cursor='pointer';
.
}

The premium suggestion would be to add the tags when you generate the table. If you need to do it after the table is rendered and you want to use javascript you can always add something like
var mytable = document.getElementById("theTable")
var myrows = mytable.rows
for(i=0;i < myrows.length;i++)
{
var oldinner;
oldinner = myrows[i].cells[0].innerHTML;
myrows[i].cells[0].innerHTML = "<a>" + oldinner + "</a>";
}
or if you need to do it to every cell, your can always
var mytable = document.getElementById("theTable")
var myrows = mytable.rows
for(i=0;i < myrows.length;i++)
{
mycells = myrows[i].cells;
for(a=0;a < mycells.length;a++)
{
var oldinner;
oldinner = mycells[a].innerHTML;
mycells[a].innerHTML = "<a>" + oldinner + "</a>";
}
}
I hope you find this helpful

<tr><td><a></a></td></tr>
this?

jQuery.wrap the returned anchor to a td and then add to tr and jQuery.appendTo table
$('ith anchor element in array').wrap('<td />').wrap('<tr />').appendTo('table#table_id');

You can simply gen the with and inside as Nicole suggested:
<tr><td>title of the url</td></tr>
Or put the url in the tr tag like
With jQuery included
$('tr.clickable').click(function(){
window.location = $(this).attr("title");
});
to bring you to that page on click (basically hacking a tr to work like a tag (just a thought, never really try it.

add in
and change display style to display:block
and add same size for like this:
CSS:
#Table a {
display:block;
}
#Table td {
width:100px;
hright:100px
}
HTML:
<table id="Table">
<tr><td><a onclick="" href="#"> cell </a></td></tr>
<tr><td> cell </td></tr>
</table>

You can use data-href script to add href in any html elements. It makes html valid since it add only data-href attribute to a element.
https://github.com/nathanford/data-href/

Related

Delete table rows if table data does not contain a specific class

I got a question regarding removing table rows within a table. I got the following HTML:
<table>
<tr>
<td class="html5badge">autofocus</td>
<td>autofocus</td>
<td>Specifies that the drop-down list should automatically get focus when the page loads</td>
</tr>
<tr>
<td>disabled</td>
<td>disabled</td>
<td>Specifies that a drop-down list should be disabled</td>
</tr>
<tr>
<td class="html5badge">test</td>
<td>autofocus</td>
<td>Specifies that the drop-down list should automatically get focus when the page loads</td>
</tr>
</table>
I need a mechanism that looks whether the first <td> does not contain the html5badge class and delete the parent: <tr>.
To do this I created the following jQuery code:
$(document).ready(function() {
$(".onlyhtml5").click(function(event) {
event.preventDefault();
var classname = $('table tr td').not('.html5badge');
console.log(classname)
for (i = 0; i < classname.length; i++) {
$(classname[i].parentNode).remove();
}
});
});
This works but it does not exactly what I want. As you can see in my JSFIDDLE it will delete all the table rows. But what I want is the following desired output:
<table>
<tr>
<td class="html5badge">autofocus</td>
<td>autofocus</td>
<td>Specifies that the drop-down list should automatically get focus when the page loads</td>
</tr>
<tr>
<td class="html5badge">test</td>
<td>autofocus</td>
<td>Specifies that the drop-down list should automatically get focus when the page loads</td>
</tr>
</table>
The desired output is that the <tr> that contained the text: disabled is been removed! Based on the fact that the <td> within this <tr> does not contained the class: html5badge.
How can I achieve this?
You can use filter() to retrieve the tr elements which do not contain td.html5badge and remove them:
$(".onlyhtml5").click(function(e) {
e.preventDefault();
$('tr').filter(function() {
return $(this).find('td.html5badge').length == 0;
}).remove();
});
Updated fiddle
simply make it
$(document).ready(function() {
$(".onlyhtml5").click(function(event) {
event.preventDefault();
$('table tr td').not('.html5badge').each( funtion(){
$( this ).parent().remove();
} );
});
});

javascript get external table row on click

I have a button:
<button id="external-list-row">Test</button>
in which I would like to change with a row from an external table on click. The external table is structured like this;
<table id="table_id">
<thead>
<tr>
<th>X</th>
<th>Y</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p>Row 1</p>
</td>
</tr>
<tr>
<td>
<p>Row 2</p>
</td>
</tr>
<tr>
<td>
<p>Row 3</p>
</td>
</tr>
</tbody>
</table>
So my question is this; how can I replace "Test" in the button with the content of Row 1 with javascript?
As for the javascript, I'm not sure how I can get the content from row 1, and replace the button with it.
<script>
var rows = document.getElementById('table_id').getElementsByTagName("tr");
for (var i=0; i<rows.length; i++) {
$('#external-list-row').onclick = function() {
}};
</script>
Post comments:
I can access table data from other tables within the same html file, but I still don't know how to access data from tables in other html files. For example, if I try to access a videos liquid file from another liquid file, like photos, nothing happens when I press the button.
Fiddle of current code. It can replace the content of a list with the content of another, but the lists need to be on the same html file.
https://jsfiddle.net/hgnymydL/
Well, the first thing you should understand, is that a table element has a rows property, so getting the first row is trivial.
var table = document.getElementById("table_id");
var firstRow = table.rows[0];
From there, you can use textContent to get the text content of the row. I believe that's what you were looking for.
You can also select the first row of a table with a CSS selector like so:
var firstRow = document.querySelector("#table_id tbody tr");
$('#external-list-row').on('click', function() {
$(this).text($('#table_id tbody tr:first').text());
});
If you want to replace the button text with contents of the First Row ONLY then:
$('#external-list-row').html($('tr:first-child').html);
Of course you could wrap this in any event, so for example, on clicking the button:
$('#external-list-row').on('click', function() {
$(this).html($('tr:first-child').text());
});
BUT, based on the code you have given, I'm assuming you want to change the text after each click in which case you could do this:
var clickNumber = -1;
$('#external-list-row').on('click', function(event) {
clickNumber = clickNumber + 1;
//console.log('\n\nclickNUmber' + clickNumber);
$('tbody tr').each(function(index, el) {
//console.log('index: ' + index);
var block = $(el).find('td p');
if(index == clickNumber) {
//console.log('entered if')
//console.log(block.text());
//console.log('----clickNUmber' + clickNumber);
//console.log('index: ' + index);
//console.log(el);
$('#external-list-row').html(block.text());
}
});
});
jsFiddle: https://jsfiddle.net/zmb2b37t/
Hope that helps!
If you are wanting to replace the visible text "Test" in the button with the content of the cell clicked:
var tbl = document.getElementById('table_id');
var btn = document.getElementById('external-list-row');
tbl.onclick = function(ev){
var trgt = ev.target;
if(trgt.tagName === 'P' ||trgt.tagName === 'TD'){
btn.textContent = trgt.textContent;
}
};
Only one event handler is attached in this scenario.
Via event delegation we determine if it was a TD or P element that was clicked. If the rows are modified the function will still work.
Here is jquery code of do this
$('#table_id tr td').on('click', function(){
$('#external-list-row').html($(this).html());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="external-list-row">Test</button>
<table id="table_id">
<thead>
<tr>
<th>X</th>
<th>Y</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p>Row 1</p>
</td>
</tr>
<tr>
<td>
<p>Row 2</p>
</td>
</tr>
<tr>
<td>
<p>Row 3</p>
</td>
</tr>
</tbody>
</table>

Multiple elements with same Id in Javascript

I have a case where a html file contains multiple elements with the same ID name.
The table row contains 5 columns of which I need to consider 2,3,4,5 columns data.
<tr id='total_row'>
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
I have the above code at several places in the file. I need to add the respective values using javascript.
An ID is unique in an html page. You can call it THE ID as well wrt a page. You cannot have same ID for two different tags in a single page. But you can use class instead of and ID. Know about it here
So your HTML can be like
<tr class='total_row'>
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
As an example with jquery you can do something like this,
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<table>
<tr class="one">
<td></td>
<td></td>
</tr>
<tr class="one">
<td></td>
<td></td>
</tr>
<tr class="one">
<td></td>
<td></td>
</tr>
</table>
<script src="jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
$(".one").eq(0).find('td').eq(0).html("I'm tracked");
// get 1st tr and get first td
$(".one").eq(1).find('td').eq(1).html("I'm tracked");
// get 2nd tr and get second td
$(".one").eq(2).find('td').eq(0).html("I'm tracked");
// get 3rd tr and get first td
});
</script>
</body>
</html>
But I guess this approach can be tedious.
Id should be unique and if you use the same id, javascript code refers only the first element. but if you still want to use same id than you may try the below code:
$(function(){
$('[id="total_row"]').each(function(){//run for every element having 'total_row' id
var $this = $(this);
$this.find('td').eq(1).text() //to get second column data
$this.find('td').eq(1).text('dummy text') //to set second column data
});
});
You can use XHTML:
<p id="foo" xml:id="bar">
Through XHTML you can apply similar ID to multiple Controls.
Similar questions can be found here:
http://www.c-sharpcorner.com/Forums/
While duplicate IDs are invalid, they are tolerated and can be worked around. They are really only an issue when using document.getElementById.
I'll guess that the table looks like:
<table id="t0">
<tr>
<td>-<th>count<th>Pass<td>Fail<td>Error<td>
<tr>
<td>-<td>1<td>1<td>0<td>0<td>
<tr>
<td>-<td>1<td>1<td>0<td>0<td>
<tr id='total_row'>
<td>Total<td><td><td><td><td>
<tr>
<td>-<td>1<td>1<td>0<td>0<td>
<tr>
<td>-<td>1<td><td>1<td>0<td>
<tr>
<td>-<td>1<td><td>0<td>1<td>
<tr id='total_row'>
<td>Total<td><td><td><td><td>
</table>
<button onclick="calcTotals();">Calc totals</button>
If that's correct, then a function to add each sub–section can be like:
function calcTotals(){
var table = document.getElementById('t0');
var rows = table.rows;
var row, totals = [0,0,0,0];
// For every row in the table (skipping the header row)
for (var i=1, iLen=rows.length; i<iLen; i++) {
row = rows[i];
// If it's a total row, write the totals and
// reset the totals array
if (row.id == 'total_row') {
for (var j=0, jLen=totals.length; j<jLen; j++) {
row.cells[j+1].innerHTML = totals[j];
totals[j] = 0;
}
// Otherwise, add values to the totals
} else {
for (var k=0, kLen=totals.length; k<kLen; k++) {
totals[k] += parseInt(row.cells[k + 1].innerHTML) || 0;
}
}
}
}
In addition to using classes, which works but feels kind of icky to me, one can also use data-* attributes.
<tr class='total_row' data-val-row-type="totals-row">
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
Then, in your script (jQuery syntax -- querySelectorAll has a similar syntax)
var $totalsRows = $("[data-val-row-type='totals-row']);
When you are in a team with a separate UI designer, this keeps the UI guy from ripping out and changing your class names to fix the new design layout and it makes it quite clear that you are using this value to identify the row, not just style it.

Delete row from table using JQuery. Please see code

I used a code which I got in the net that adds a table row every onclick event. It worked perfect for me until I realized I needed to have an onclick event for every row that when clicked, it will delete the row.
Is there a way for that to happen using my code?
Please see codes below:
Javascript/JQuery code:
<script>
var counter = 2;
function addRow() {
event.preventDefault();
var newRow = jQuery('<tr><td><label>'+ counter +'</label></td><td><textarea name="txtActionStep' + counter + '" style="width:300px; height: 50px; word-wrap:break-word;"></textarea></td><td valign="top"><input type="text" name="txtOwner' + counter + '"/></td></tr>');
counter++;
jQuery('table.actionsteps-list').append( newRow );
}
</script>
HTML Code:
<table class="actionsteps-list" width="510">
<tr>
<th colspan="3" align="left">Action Steps</th>
</tr>
<tr>
<td>Step #</td><td>Action Step</td><td>Owner</td>
</tr>
<tr>
<td><label>1</label></td>
<td><textarea name="txtActionStep1" style="width:300px; height: 50px; word-wrap:break-word;"></textarea></td>
<td valign="top"><input type="text" name="txtOwner1" /></td>
</tr>
</table>
<table width="510">
<tr>
<td align="right">Add Action</td>
</tr>
</table>
Thank you!
Sure, using delegation we can accomplish that.
$('table.actionsteps-list').on('click', 'tr', function(e){
$(this).remove();
});
You probably want to add a button to your row to signal a deletion, so let's assume you add (to each row):
<td><button class="delete">Delete</button></td>
Then just change your delegation method like this:
$('table.actionsteps-list').on('click', '.delete', function(e){
e.preventDefault(); // stops the page jumping to the top
$(this).closest('tr').remove();
});
Use a delegate ot catch the event at the table level, that way any new row that you add will also be handled:
$('.actionsteps-list').on('click', 'tr', function(){
$(this).remove();
});
Side note:
Don't use the javascript: protocol for inline Javascript, that's only used when you put Javascript in the href attribute of a link:
Add Action

How to detect if a table contains a table?

I have multiple tables need to be nested with divs
Like this:
<table>
<tr>
<td>
<table>
<tr>
<td>EEE</td>
<td>EEE</td>
</tr>
</table>
</td>
</tr>
</table>
Then, I get each table with the code below:
var isert = inn.getElementsByTagName("table");
for(var i = 0 ;i<isert.length;i++)
{
var div = document.createElement("div");
var _t = isert[i];
var parent = _t.parentNode;
div.className = "extra";
parent.replaceChild(div, _t);
div.appendChild(_t);
}
}
So the table becomes:
<div class="extra">
<table>
<tr>
<td>
<div class="extra">
<table>
<tr>
<td>EEE</td>
<td>EEE</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
However, after I adding css styles to class "extra", they are overlapped. So what I need is a method like below to detect whether this table contains a table inside.
if( ! 'table' contains 'table'){
...adding the div...
}
I hope this could be solve by pure JavaScript. Thanks!
I don't know what kind of themes you're working with, but you would conceivably be able to solve this with pure CSS
table { some theme style; }
table table { revert to default style; }
EDIT
From what I understand after your update, you want to turn the following code int something that doesn't rely on jQuery, correct?
var curr = $(this);
if(!curr.has('table').length) {
getElementsByTagName is available on all tag nodes and will only yield child elements, so you could do that check as follows:
if(!curr.getElementsByTagName('table').length) {

Categories