I have a table that automatically adds new rows, once u go to the last cell and tab over.
I click on one of the cells - I want to know the rowIndex of the clicked cell (row)
I havent been able to uniquely identify the cell using any attribute eg classname etc, ID is randomly generated. Name , TagName everything is generic - Same for all rows.
How do I get the rowIndex just using a cell's info
No jquery sols pls - not allowed in my framework
You can grab this info from the parent node tr as rowIndex:
td.parentNode.rowIndex
Here td is HTMLTableCellElement element.
td has a reference to its parent row element parentNode (tr), which in its own turn has a property rowIndex. Similarly td itself has a property cellIndex.
Demo: http://jsfiddle.net/prFSd/1/
dfsq provides a good answer, but it uses jquery which you said you could not use. You could put this in each rowonclick="myFunction(this)"then define the function
function myFunction(x)
{
alert("Row index is: " + x.rowIndex);
}
Related
I am trying to get the column name when the user clicks on the jquery datatable's footer cell.
I tried to follow this: https://datatables.net/forums/discussion/24593/retreive-column-idx-when-clicking-on-header
And, https://datatables.net/reference/type/column-selector
But, I am getting 'undefined' with the following code,
$('#myTable').on( 'click', 'tfoot th', function () {
var index = table.column( this ).index(); //index is returned as undefined
} );
Any suggestion will be greatly appreciated.
CAUSE
Columns can be selected only if you use header th nodes or table body td nodes, that's why it doesn't work.
SOLUTION
Try the code below to get actual column index.
Modifier :visible is needed because $(this).index() operates with actual DOM elements and returns index of the th node among currently visible columns. However jQuery DataTables may remove columns from DOM when using various extensions, such as Responsive, Buttons - Column visibility, etc, and actual column index may differ from index of the column in DOM.
$('#example').on( 'click', 'tfoot th', function () {
var index = table.column($(this).index() + ':visible').index();
});
See this example for code and demonstration.
I want to get a text of cell in a tr row.
The tr row has class attr and a data- attr.
I select the tr row as
var k = $('tr[class="BatchTypesRow"][data-rowselected="true"]');
then
var m = k.children("td:first");
var sBtype = m.text();
alert(sBtype);
the sBtype contains all cells' text in the row.
I tried
var sBtype = m[0].text();
that catches an exception.
So what is the problem here?
If the cell is not the first cell in the row, how to do it?
Here, m itself is the first td of the row since var m = k.children("td:first");
So m.text() would not give the whole row as long as td:first is selected. If you use .children("td") then you would be getting the whole row in m.text(). So in your code,
var sBtype = m.text();
alert(sBtype);
would actually give the First cell content.
If not the first cell, you would be using var m = k.children("td"); removing the keyword first. In this case m[0] would have the first cell, m[1] second and so on.
Correct me if am wrong, I believe this is how you got the exception, using m[0].text() would throw you an exception since m[0],m[1] are not JQuery object. They are HTMLTableCellElement Object.
To use it as a JQuery object, you would have to use $(m[1]).text().
And if you know which element to be selected w.r.t its sequence, you can use
var m = k.children("td:nth-child(n)");
where you can replace n with the number so that you will select the nth td of the row.
Hope this helps.
$('tr.selected td:first-child').text();
Firstly, select the tr within which lies the text.for which you can use the class attr
$("tr.BatchTypesRow")
then traverse down the tree to get the td ie its children
$("tr.BatchTypesRow").children("td")
as you need the first child ,is the first td as you traverse through the selected tr ,it can be further written as
$("tr.BatchTypesRow").children("td:first")
if the text lies within a label inside the selected td
$("tr.BatchTypesRow").children("td:first").children("label").text();
will give you the desired text .
Here is the question I tried to learn from
jQuery selector to grab cells in the same column
Before any of the answers using index and nth-child had been proposed I was thinking along the lines of counting number of cells before $(this) cell - e.g.
var columnNo = parentRow.nextUntil($(this),"td").length;
console.log(columnNo); // gives 0 - what am I missing?
parentTable.find("tr td:nth-child(" + (columnNo+1) + ")")
http://jsfiddle.net/mplungjan/JUt4F/
Questions:
why does the nextUntil not give the length of the preceding cells?
2. why does the click only work once?
Please note that I know (before asking this) I can use index. I just wanted to fix my script to explore nextUntil
UPDATE: I seem to mix nextAll and nextUntil and likely imagined some kind of nextAllUntil
The nextUntil() method will find the first td tag in the parent row. With that logic, you're only going to select the first cell in each row. The click is working everytime--you're just coloring the same column red over and over.
What you need to do is search for all td tags on the parent row and use jQuery's index() method to identify the position of the clicked cell in that row.
A very small tweak will fix the problem:
$("td").on("click",function(){
var parentTable = $(this).closest("table");
var parentRow = $(this).parent();
console.log(parentRow);
var columnNo = parentRow.find('td').index($(this));
console.log(columnNo);
parentTable.find("tr td:nth-child(" + (columnNo+1) + ")")
.css("color", "red");
});
Working example: http://jsfiddle.net/JUt4F/15/
If I have a table
<table id="myTable"><tr><td>First Thing</td><td>First Value</td></tr>
<tr><td>Second Thing</td><td>Second Value</td></tr>
<tr><td>Third Thing</td><td>Third Value</td></tr>
</table>
How can I use JQuery or javascript to search to get the index of the row with text "Second Value" and remove it? Also is it possible to create a new row
<tr><td>Fourth Thing</td><td>Fourth Value</td></tr>
with the click of a button? Will I have to iterate through the existing rows to get the last index of the row to insert it in?
You can achieve this easily using the :contains() selector, the remove() function, and the append() function. You don't need to iterate through the rows to find what you're looking for.
To get the index:
$("#myTable").find("td:contains('Second Value')").parent().index();
To remove it:
$("#myTable").find("td:contains('Second Value')").parent().remove();
To add a row:
$("#myTable").append("<tr><td>Fourth Thing</td><td>Fourth Value</td></tr>");
working example: http://jsfiddle.net/hunter/PzJWC/
You should ideally generate id's per each tr/td - but thats if you getting data dynamically i suppose.
If you know the order of your tables then you can use these sleectors from jQuery
$('tr:last-child').html('<p>This is the absolouty last tr in the WHOLE page<p>')
$('tr:nth-child(even)').addClass('evenColors')
$('tr:nth-child(4n)').remove() //Removes the 4th from the top TR DOM Element
var theValueOf = $('tr:first-child').html() //assigns the innerHtml to your var
So if you have 10 tables each table should have an id or class
<table id="table1"> ...bla... </table>
$('table1 tr:last-child').remove() //Remove last TR from Table1
You will need to structure your html more with id's and classes
In your case you will have to restructure your table some how programatically to atach unique ids to each row then use jquery to select it. This is ideal world
But you do a loop and check each inner html until what you want and do a .remove()
But to get the INDEX use hunters reply! But from experience this is a headache on large and dynamic documents.
JQuery has .insertAfter and insertBefore. For targeting you can also use nth-child css selector or if you want it dynamic (like insert a row after the row they click) you can use the 'this' operator and some dom navigation. All that said be very careful when editing tables on the fly, they have some peculiarities about where things can be inserted and are heavy on performance.
i just did it ;)
to add row (you may not want to use append because your table may have tbody etc):
$('#myTable tr:last').after('<tr id="forth_row"><td>forth thing</td><td>forth value</td></tr>');}
to find and remove that row:
$('#myTable').find("#forth_row").remove();
I currently have a big problem with the rowIndex in the IE8. When I call the page I have an empty table element. With Javascript I now add Rows and Columns to this table.
// Create Elements
tr = document.createElement('tr');
td = document.createElement('td');
// Append Elements to existing Table
tr.appendChild(td);
table.appendChild(tr);
The User later has the Option to delete these Rows. To delete them I simply call the deleteRow Function of the table and pass the rowIndex as a parameter.
table.deleteRow(tr.rowIndex);
In the Firefox this works fine. The rowIndex is correct and the rows can be deleted. In the IE8 the rowIndex ALWAYS is -1. The deleteRow function - of course - can't find the matching row and the row isn't deleted.
Does anyone know this problem and has a nice solution for this?
IE will still give you a -1 rowIndex if the row is in a table but the table is not attached to the document.
You could fix it by adding the table to the document, but it's probably easier to avoid the problem by simply using the generic DOM Level 1 Core method instead of the table-specific DOM-HTML methods:
tr.parentNode.removeChild(tr);
It's probably also best to create a tbody element and put the rows in that; otherwise browsers may unexpectedly do it for you.
You might try removeChild.
That is as easy as:
table.removeChild(tr);