How can I get a clicked table row's TBODY? - javascript

I have a table with a few rows in it. Each row has an onclick event that is supposed to check the ID of the tbody element. This is stored in a variable for later use in a function.
Right now I have this snippet of jQuery:
var parentTable = $(this.parentNode)[0].id;
However, this only gets the ID of the entire table, not the tbody.
What's the best way to specify the ID of the tbody element?

First, your use of jQuery is wasted there. It would be written like this:
var parentTable = this.parentNode.id;
As far as getting the tbody id, assuming this is actually the row, your code should do it.
If you're actually getting the table, then that would be very unusual. The only way a tbody would not get created would be if you manually created the table from DOM creation methods, and left it out.

You may want to store that information in a data-tbody-id for each row, then when the user clicks on the row, the event object will hold that information.

You can use the following function
var tobody = parentTable.children('tbody')

You can use the following function
var tbody = $(this).parents("tbody");
var id = tbody.attr("id");

Related

jQuery: accessing a single instance of a class in a dynamically created table

I have many auto-generated table and those tables have a <span class="productNumber"> element in the thead that shows the number of products in the table. (right now this is done in php via <?php count($products); ?>).
I wrote a filter to help users to navigate those tables. The filter allows the user to choose a product category and all tr elements that don't have this product category get the Bootstrap class hidden.
I now want to use jQuery to count the actually visible elements for each table and display the number of elements that are actually visible.
My current approach is this:
$('table').each(function(){
let counter = 0;
$('tr', this).each(function(){
if (this.hasClass("hidden")) {
counter++;
};
});
$('.productNumber').html(counter);
})
The problem is that this overwrites all .productNumber elements with the same value (the number of visible products in the very last table).
I tried modifying it in various ways ($('.productNumber', this), $('.productNumber')[0], etc.), but wasn't able to write only to the current table's .productNumber.
The easy way to do this:
$("table").each(function(){
var count = $(this).find("tr:not([class*='hidden'])").size();
$(this).find(".productNumber").first().html(count);
});
English Translation:
For each table:
Get the number of tr's that don't have "hidden" defined in
it's class attribute and assign to the count variable.
Find the first ".productNumber" cell in the table and set its
content
use this selector
$(this).children('.productNumber').html(counter);
My proof of concept. https://jsfiddle.net/dewwwald/8gn5jdsL/1/
The issue is solved by specifying the this to the product number lookup.
assuming productNumber is inside the tr. Also as you describe your requirements I read that this.hasClass("hidden") should have a ! so !this.hasClass("hidden").
$('table').each(function(){
let _this = this;
_this.counter = 0;
$('tr', _this).each(function(){
if (!this.hasClass("hidden")) {
_this.counter++;
};
$('.productNumber', this).html(_this.counter);
});
})

How do you hide the first element in the first table?

I know that to hide the first element in a table is simply do (':first-child') but is there a way to specify that only the first element of the first TABLE needs to be removed?
In my situation the first element of every table is being hidden and I need to fix this.
I suppose you just target the first table, and then the first element, whatever that is ?
document.querySelector('table tr').style.display = 'none';
FIDDLE
as querySelector gets the first matching element, or in jQuery
$('table:first tr:first').hide()
FIDDLE
target the first table and the first td.
$('table:first td:first').hide()
DEMO
You can get a collection of all tables using document.getElementsByTagName("table"). Element zero of that collection ([0]) is the first table. You can then apply your first-child solution to element zero.
This does not require jQuery, nor that you assign an ID attribute to a specific table. (Assigning an ID attribute is probably more efficient if you know in advance which table is going to be first.)
Edited to add: I've tested this and it works, although it is revised from my first "it works" post. The first child element of TABLE is TBODY for a table that starts with a tr element, so what is really wanted is the first child of TBODY. It is probably better to descend the firstElementChild tree looking exspressly for a nodeName of "TR" and hide that. Look further down in this post for that approach.
Here is the simple code that works:
document.getElementsByTagName("table")[0].firstElementChild.firstElementChild.style.display = "none";
This is pure JavaScript, with no need for jQuery. Note that document.getElementsByTagName returns a live collection, so even if a table is added to the DOM, this will get the first one.
Do remember that the first element child of <table> (and then TBODY) is not necessarily <tr>. If you can be sure it is, or if you want the first element regardless, then what I've given will work for you. If you want to be sure it's a <tr> then a little more work will be needed.
This code finds and hides the first <tr> but will be less efficient because it gets two HTML collections:
document.getElementsByTagName("table")[0].getElementsByTagName("tr")[0].style.display = "none";
const tables = document.getElementsByTagName("table")
const firstTable = tables[0];
const firstRow = firstTable.rows[0];
firstRow.style.visibility = "hidden"; //hide
firstRow.style.visibility = "visible"; //visible
Here is a referrence.

jQuery: closest / parent not working

I have a basic HTML table with a button in each row.
By click on the button I want to alert the text from the second TD in the same TR.
For some reason the below does not work and either returns nothing or null (depending on whether I try .text() or .html() ). parent instead of closest failed as well.
Can someone tell me what I am doing wrong here ?
(My table has the ID "myTable" and all TRs are in a TBODY, if needed.)
Example TR:
<tr><td style="width:30%"><strong>Row 1:</strong></td><td id="fldRow1" style="width:60%">test text</td><td><button type="button" id="copyRow1" onclick="copyOutput()">Copy</button></td></tr>
JS function:
function copyOutput() {
var output = $(this).closest('tr').find('td:eq(1)').text();
alert(output);
}
Many thanks for any help with this, Tim.
thisin you code not refer to the current element it refers to the window object.
HTML
Change
onclick="copyOutput()"
to
onclick="copyOutput(this)" //pass refer of the current element
js
function copyOutput(el) { //el get current element clicked
var output = $(el).closest('tr').find('td:eq(1)').text();
alert(output);
}

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

Categories