Selector - Selecting all tables on a page in jQuery - javascript

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.

Related

jQuery remove tr with no results

I have a SQL-PHP printed table, and a select at the top of the table. The table contains contacts classified by towns.
At the beginning, the table shows all contacts. If I specify the town, I want to hide the rest.
I'm trying to use a jQuery script
<script>
function updateit(){
if ($("#table").filter("tr") === $("#selectTown").val()) $(this).show(););
else {$(this).hide();};
}
</script>
[...]
<select id="selectTown" onchange="updateit()"><option value="NY">New York</option><option value="TX">Texas</option></select>
<table id="table">
bla bla bla...
</table>
Before I tried with find() function, but with no success.
Any suggestions?
This line $("#table").filter("tr") === $("#selectTown").val() compares document elements to string, it would not work.
Simplest solution would be to do all elements hidden and than select and show all matching elements. Example:
$('tr').hide();
$('tr[value=' + $("#selectTown").val() + ']').show();
I'm not sure where you got the idea for this code, but filter() definitely doesn't do what you think it's doing. $("#table").filter("tr") is going to give you a list of tr elements in the table. That list itself isn't going to equal any selected value, it's just an array of elements.
Mocking up a few things in a jsFiddle here, perhaps you want something more like this:
$('#selectTown').change(function () {
$('#table tr').hide();
$('#table tr').filter(function () {
return $(this).find('td:first').text() === $('#selectTown').val();
}).show();
});
What this does is:
Bind to the change event of the select element (which is preferred over the inline binding you do in your markup, just in general).
Hide all of the tr elements first, you'll show the ones you want in a moment.
Show all of the tr elements which match the filter.
The filter in this case is a function which returns true if the text inside of the td element (you will likely need to update that selector) equals the selected value. The main difference here vs. what you tried is that .filter() is returning a list of matched (filtered) elements, not an actual value to compare. Internal to the filter is where the comparison takes place, in this case using a function (which needs to return true or false for any given element being filtered).

Remove table rows using jQuery but prevent remove the first row

I am using jQuery to remove table rows - my script works ok but I don't want the button to be able to remove the very first table row. Can anyone suggest how this is done?
$("#remove").click(function(event) {
event.preventDefault();
$("table tr:last").remove();
i++;
});
Try the following:
if ($("table tr").length != 1) {
$("table tr:last").remove();
}
How about
$("tr:last:not(:first)").remove();
You don't need the table selector as all rows are inside tables, but it might be useful to specify the table element from which you want to remove (avoiding side effects if you later would add other tables).
Example: Remove all rows from $table except the first:
$("tr:not(:first)", $table).remove();
You can use gt() and not():
$('table').find('tr:gt(0):last').remove();
This finds all rows with an index greater than 0, gt(0) and selects the last row, :last and then removes that element.
Demo: http://jsfiddle.net/XhtC8/
If you wanted to remove all rows but the first then you can remove :last:
$('table').find('tr:gt(0)').remove();
Try:
$("#remove").click(function(event) {
event.preventDefault();
$("table tr:not(':first')").remove();
i++;
});
Demo here: http://jsfiddle.net/aGukb/

jQuery syntax for finding row index in a HTML table

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

How to get table row above (or before) my current row in jQuery?

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

jQuery remove range of rows

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

Categories