1) How do I find the row number/index in a HTML table? The generated table doesn't have any id for row.
eg: I have a plain HTML table generated, which has 10 rows,
I am adding rows dynamically to this table.(in between existing rows)
Since I am adding new row, the existing row index will change. Now I need to to find the index of each row before adding the new row.
"1) How do i find the row number/index in a HTML table? The generated table dosen't have any id for row."
If you mean that you already have a row, and you need its index, don't use jQuery to get it. Table rows maintain their own index via the rowIndex property.
$('table tr').click(function() {
alert( this.rowIndex ); // alert the index number of the clicked row.
});
Demo: http://jsfiddle.net/LsSXy/
To get the index of any element within a selector use index().
In your case it would be:
var rowIndex = $("#myTable TR").index();
In addition, you can use eq() to select a specific element in a group:
var thirdRow = $("#myTable TR").eq(2) // zero based .: 2 = 3rd element.
Read more on info
Read more on eq
The jQuery site is really good for finding functions, I always find myself going back to it all the time for reference and refresh. http://docs.jquery.com/
Or you can use css selectors in jquery like so
$('table tr td:first').addClass('first-row');
Related
I'm trying to find the index of a HTML table row that contains a given ID, the ID is in a known column (the last column). It needs to check if the table has that ID and then ultimately delete the row - I've come up with the following to find the index but I always get an index of -1
var index = $('#myTable td:contains(' + ID + ')').index($(this));
Any suggestions would be much appreciated, thanks
You don't need the index to remove a row. You can use the :contains selector to find the td then simply call remove() on the parent tr element:
$('#myTable td:contains("' + ID + '")').closest('tr').remove();
You need to find the TR element from your searched TD. You can step backward one step by issuing the closest() method.
So, you can find the index of the row the following way. Remember, index starts at 0:
var index = $('#myTable td:contains(' + ID + ')').closest("tr").index();
You can directly remove the TR also with the following line of code. This will remove all rows that contains ID in any cell:
$('#myTable td:contains(' + ID + ')').closest("tr").remove();
I have a table named resultGridTable. I have a jQuery function to be executed on each row of the table. In the function, "this" means a row.
For the fourth row, I need to alert the first column value (of fourth row). I have the following code; but it does not work. How can we make it working?
For the fifth row, I need to alert the number of columns in the row. How can we do it?
In the sixth row's second column, I have two buttons (input type="submit"). I need to alert the second button's text/value. (The second button has a class named "secondButton") How can we do it?
Following is the code::
$('#resultGridTable tr').each(function (i)
{
//"this" means row
//Other operations in the row. Common for all rows
if(i==3)
{
//Specific Operation for fourth row
var columnValue = $(this 'td:nth-child(0)').val();
alert(columnValue);
}
});
READINGS:
jQuery Code: Starting from Parent to Child; not from Child to Parent
How to get value of first column in current row in html table using jQuery
How to get the first row's last column of an Html table using jQuery
Just to be different, you can mix up DOM and jQuery to good effect here since you have fixed offsets into the table:
var t = document.getElementById('resultGridTable');
// jQuery to get the content of row 4, column 1
var val1 = $(t.rows[3].cells[0]).text();
// no jQuery here to get that row length!
var val2 = t.rows[4].cells.length;
// DOM access for the cell, and jQuery to find by class and get the text
var val3 = $('.secondButton', t.rows[5].cells[1]).text();
These should all be substantially faster than using selectors.
Look into jQuery eq:
alert($('#resultGridTable tr:eq(3) > td:eq(0)').text());
alert($('#resultGridTable tr:eq(4) > td').length);
alert($('#resultGridTable tr:eq(5) > td:eq(1) > .secondButton').text());
If you have special values for rows/columns, consider adding a class to it, then you can use selectors rather than "magic" numbers which could change.
Adapted from Accepted Answer.
This is the code if you are using jquery instead of document.getElementById The difference is that you need to insert the array of [0].
var t = $('resultGridTable');
// jQuery to get the content of row 4, column 1
var val1 = $(t[0].rows[3].cells[0]).text();
Say I have a variable which holds a table row.
How would I get the row right before it using javascript/jquery?
This:
var prevRow = row.previousElementSibling;
or
var prevRow = $( row ).prev()[0];
([0] is used to "unwrap the jQuery object", to get the DOM reference to that row. If you want to perform jQuery methods on that row, you can just leave it inside, like $( row ).prev().addClass( '...' ); and in that case you don't need a new variable.)
Assuming that the two rows are siblings (not contained in separate tbody or thead elements):
$curRow = $(this); // or however you're getting the current `tr`.
$curRow.prev('tr');
Should get you the previous row.
Well you need to do something like so:
$("#cellID").parent().prev()
Your input is not sufficient but if i understand correctly here is the code for your requirement..
If your Variable contains table row id then $('#yourVariableName').prev('tr')[0] will work.
If your Variable contains table row Class then $('.yourVariableName').prev('tr')[0] will work.
If your Variable contains table row index then $(' table tr').eq(varValue).prev('tr')[0] will work.
But please specify what your variable will contain.
Let's say you want to get the input value from the td in the tr above the current one:
$('#id').prev().children('td').children(':text').val();
Let's say I have a table with these rows:
<table>
<tr id="before_dynamic_rows"></tr>
<tr id="after_dynamic_rows"></tr>
</table>
Using jQuery, I insert automatically generated rows (search results) before the after_dynamic_rows row. How can I delete a range of rows, namely - you guess it - the ones between the row with the id before_dynamic_rows and the row after_dynamic_rows? (In order to be able, after having inserted them, to remove them and insert different ones.)
var response = ajax.responseText;
$('#after_dynamic_rows').before(response);
That's how I insert the new rows. Considering the first answer: how can I assign a class to whatever the response text may be?
This answer is based on a literal interpretation of the question with the idea that the only rows which should be removed are those rows that are in between #before_dynamic_rows element and #after_dynamic_rows.
See working version at: http://jsfiddle.net/7wBzd/
var $rows = $("tr");
$("tr:lt("+ $rows.index($("#after_dynamic_rows")) +"):gt("+ $rows.index($("#before_dynamic_rows")) +")").remove();
$("table tr:gt(0)").not("#after_dynamic_rows").remove();
Try it out here.
Note if #after_dynamic_rows is the last row, then you can just do:
$("table tr:gt(0)").not(":last").remove();
or:
$("table tr:gt(0):not(:last)").remove();
...and if there are rows before #before_dynamic_rows, just do:
$("table tr:not(#before_dynamic_rows, #after_dynamic_rows)").remove();
I would assign a class to those added rows to make them easy to select, but you could select all tr children and use the 'not' method to remove the two you want to keep.
$("table tr").not("#before_dynamic_rows").not("#after_dynamic_rows").remove();
Say I have multiple tables (no IDs or names) on a page at various levels within embedded divs. What would my selector be (if it is possible) to select all tables regardless of where it resides on a page and iterate or filter the tables based on the content of the first cell in the first row?
You can simply use $('table') as your selector.
Then you can use the existing filters such as ":contains" or ":has", or the .filter() function if you need more finegrained control over in filtering your results. For example,
$('table:has(td > span)')
or
$('table').filter(function(index){
return $(this).html() == "<tr><td>something</td></tr>";
});
Try...
$("table").each(function(){
var curTable = $(this);
var cell = $(this).find("tr:first td:first");
if ($(cell).text() == "some text"){
}
});
alternatively you could all check the html of the first cell in the if clause by $(cell).html()
To select all tables couldn't be simpler:
$("table")
Adding a filter
$("table:has(td:first:contains('mytext'))")
This will select all the tables:
$("table")
This will select the first TD cell of the first row of each table:
$("table tr:first td:first")
You can get every table by just using jQuery('table'). Whether the tables are in various levels or embedded within divs or whatever doesn't change.
To do additional filtering:
jQuery('table').filter( function() { ... } );
The passed in function will map the table element to this, and you would need to return true to keep it in your collection, or false to discard it.
$('table').each(function(){
$(this).find('tr :first')...
});
If you are wanting to look at the first cell in the first row of each table you can use:
$("table tr:first td:first").each(function() {
var html = this.innerHTML;
/* Iterative logic here */
});
You should try something like $('table tr:first td:first:containts("whatever")') to grab the first cell of the first row with specific content.