RowIndex in Javascript - javascript

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);

Related

jquery datatable - Get column name by clicking on table footer cell

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.

How to get first td text from a tr by jquery

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 .

How to get value of child element in table cell with jquery?

I added jQuery to an older application. This is causing some syntax errors so I need to update the older code to be compatible with jQuery. For clarification, once I include jQuery, myTable.rows.length returns "undefined." The reason I am including jQuery is because I want to use DatePicker elsewhere on the page.
Once I changed myTable.rows.length to $('#myTable tr').length; that part worked correctly, which led me to believe I need to update the following snippets as well.
What is the equivalent of the following code, in jQuery?:
myTable.rows[i].cells[0].children[0].value;
If what you are doing works, why change it?
I am not a fan of this, but the same idea would be
$("#myTableId")find("tbody tr").eq(i).find("td").eq(0).children().eq(0).val();
You would probably be better off with having a class on the item you are trying to select.
If it will be the first input in the first cell it would just be
var i = 0;
var rows = $("#myTableId")find("tbody tr");
var inputVal rows.eq(i).find("td :input").val();
It would be
$($("td:first", ($("#myTable tr")[i])).children()[0]).val();
To select the k-th td:
$($($("td", ($("#myTable tr")[i]))[k-1]).children()[0]).val();
Somewhat simpler ( i-th row, j-th cell ):
$("#myTable tr:nth-child("+i+") td:nth-child("+j+")").children()[0].val();

Get table rowIndex of a HTML table without traversing - Only Javascript

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);
}

How do I search and remove/append a row in Jquery or Javascript?

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();

Categories

Resources