How to get row id from row Index in table using JavaScript - javascript

Suppose this is my table:
<table>
<tr id="a">
<TD>a</TD>
</tr>
<tr id="b">
<TD>b</TD>
</tr>
</table>
How can I get row id using the row index from a table?
Above is just an example where id is static but in my case my id is dynamic, so I can't use
document.getElementById().

Assuming you have only one table on your page:
document.getElementsByTagName("tr")[index].id;
Preferably though, you'd give your table a id, though, and get your row like this:
<table id="tableId">
<tr id="a">
<td>a</td>
</tr>
<tr id="b">
<td>b</td>
</tr>
</table>
var table = document.getElementById("tableId");
var row = table.rows[index];
console.log(row.id);
This way, you can be certain you don't get any interference, if you have multiple tables in your page.

"So, How can i get row id using row Index from a table"
You would select the table, and use the .rows property to get the row by index.
var table = document.getElementsByTagName("table")[0]; // first table
var secondRow = table.rows[1]; // second row
Then you just get the ID in the typical manner.
console.log(secondRow.id); // "b"
DEMO: http://jsfiddle.net/MErPk/

Answer has been edited
With CSS3 you can use the nth-child selctor. Here the example shows the rowIndex = 2
alert(document.querySelector("table tr:nth-child(2)").id);
In jQuery you can do this with
alert($("table tr:nth-child(2)").attr('id'));
The same syntax nth-child() can be used in CSS
<style>
tr:nth-child(2) {
color: red;
}
</style>

Related

How to append td element in the same column of th element in a table?

I need to append data to a table dynamically from a JSON object.
After adding the titles as th elements, I am finding it difficult to add tr elements in the same column as the corresponding th element. Please help me.
{
"Category2":"Item2",
"Category1":"Item1",
"Category3":"Item3"
}
<table>
<th>Category1</th>
<th>Category2</th>
<th>Category3</th>
</table>
Now, I need to add items in td tags in the columns same as their corresponding th elements. like:
<table>
<th>Category1</th>
<th>Category2</th>
<th>Category3</th>
<tr>
<td>Item1</td>
</tr>
<tr>
<td>Item2</td>
</tr>
<tr>
<td>Item3</td>
</tr>
</table>
How can I do this using jQuery? (My problem is bigger than this. I simplified it so that it can be understood. Thank you!)
Here you go, Press Run code snippet and check if this works for you.
var nodes = {
"Category2":"Item2",
"Category1":"Item1",
"Category3":"Item3"
};
$(function(){
var th_elements = $('table').find('th'); // find <th> in HTML
th_elements.each(function(){ // Loop as much <th> found
var html = $.trim($(this).html()); // get HTML and compare with nodes key
$('table').append('<td>'+nodes[html]+'</td>'); // append data to table
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table>
<th>Category1</th>
<th>Category2</th>
<th>Category3</th>
</table>

Jquery select tbody but not from nested tables

I am trying to append data to a table, that gets selected using jquery. The problem is, this table may have nested tables within it. What happens is that when I append the data, not just the parent table's tbody gets appended but so too does all the children tables tbody. Here is my code:
var template = window.app.getTemplate('myTemplate');
var image = {id: imageId, name: imageName, imageList: imageTypes, extension: ext, thumbNail: thumbNailPath};
$("#MyTable tbody:first").append(template(image));
Where myTemplate is set up like this:
<tr>
<td>
<table>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
</table>
</td>
<tr>
</tr>
<td></td>
</tr>
and MyTable is set up like this:
<table id="MyTable" data-attr="images">
<thead>
</thead>
<tbody>
</tbody>
</table>
Like I said, when the append happens, if there is more than one table within tbody, all tbody's get appended to. So, how do I select only the first?
thanks
JQuery uses the CSS selectors to reach the element.
$("#MyTable > tbody:first")
E > F Matches any F element that is a child of an element E.
See more at http://www.w3.org/TR/CSS2/selector.html#child-selectors
Maybe if you update your jquery selector
$("#MyTable > tbody:first")
Try:
$("#MyTable > tbody").append(template(image));

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.

Check a table row cell for contents

I want to use jQuery to check if the 2nd cell in each table row of a table contains any text, if the 2nd cell doesn't contain any text then set the table row to display: none;
Whats the best way to go about this?
HTML:
<table id="results">
<tr>
<td>Results</td>
<td>1000</td>
</tr>
<tr>
<td>Description</td>
<td></td> <!-- This cell is empty so hide row -->
</tr>
<tr>
<td>Time/Date</td>
<td>14:03 22/01/12</td>
</tr>
</table>
Have a look at the :empty selector:
$('table tr').has('td:empty:nth-child(2)').hide()
$('table tr').each(function() {
if(!$(this).find('td').eq(1).html().length) {
$(this).hide();
}
});
This will loop through each tr, find the second element using $.eq(1) (arrays start from zero) and see if it contains anything using $.html().length. If it's empty, it hides the tr with $(this).hide().
a simple solution, make use of :empty selector
$("#results tr").find('td:eq(1):empty').parent().hide();
fiddle : http://jsfiddle.net/GHg7f/2/

Find cells that are not in the header and are only in the first column of a table using JQuery

I used to have something like,
$(elem).parents('li').find(...)
Where elem was an item in a list, so it was easy to get a reference to all of the items in the list. Now however I have added more information and decided to use a table, where the list fits into the table as follows.
[header][header][header]
[list 1][ cell ][ cell ]
[list 2][ cell ][ cell ]
[list 3][ cell ][ cell ]
I'm a little stuck creating the equivalent JQuery do a .find() on just the cells that have the list items in it. The list items are always in the left-most table cells excluding the header.
Here is what the table looks like in html.
<table id="my-table">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
<tr>
<td>list item 1</td>
<td>junk</td>
<td>junk</td>
<td>junk</td>
</tr>
<tr>
<td>list item 2</td>
<td>junk</td>
<td>junk</td>
<td>junk</td>
</tr>
</table>
Use:
$(elem).closest('tr').find(...)
If the li's are always in the first cell of each row then this should work:
$('td:first-child>li')
If you make use of thead and tbody you can find rows only in the body much easier.
Change your markup to something like this:
<table>
<thead>
... header rows ...
</thead>
<tbody>
... body rows ...
</tbody>
</table>
Then you can simply include tbody in your jquery selector to find just rows which are body rows.
Something like #my-table tbody td:first-child. Where first-child will get you the first column.
This will give you only the first column in each row.
var rows = $('tr :nth-child(1)', '#my-table').not('th');
If you want to loop through and do something to each of these now, just use:
rows.each(function()
{
//Do something with the columnn
});
The solution below will output the matching elements, first <td> in each row, to <div id="#results"
Working example at: http://jsfiddle.net/6faUf/
HTML:
<table border="5">
<thead>
<tr><th>1</th><th>2</th><th>3</th></tr>
</thead>
<tbody>
<tr><td><ul><li>List1</li></ul></td><td>2</td><td>3</td></tr>
<tr><td><ul><li>List2</li></ul></td><td>2</td><td>3</td></tr>
</tbody>
</table>
<div id="results">The list values are: </div>
JavaScript (jQuery):
$('td:first-child').each(function(){
var value = $(this).text();
$("#results").append(value);
});
If you need the cells that have the list items in them, you'd need the :has() selector, so there'd be something like that:
$(elem).closest('table').find('td:has(li) ...') — if you need all the li in the table
or $(elem).closest('tr').find('td:has(li) ...') — if you need all the li in the raw

Categories