Select the row TH of related TD - javascript

http://jsfiddle.net/wT3Ev/
How do i retrieve the text that is in the row TH of the selected td?
Yes i found some related posts, but nothing that does the trick for me.
I tried:
$(document).on("click", "#sTab td,#pvTab td", function () {
alert($('#sTab tr').find('th:nth-child(' + $(this).parent().index() + ')').innerHTML);
alert($(this).parent());
var th = $(this).closest('table').find('th').eq( this.cellIndex );
alert(th.innerHTML);
}

I'd suggest:
/* binds a click-handler to the 'tbody' element,
filters those clicks to only those that originate on a 'td' element:
*/
$('tbody').on('click', 'td', function(){
/* gets the siblings of the clicked 'td' element, filters those siblings
for 'th' elements, gets the first of those matching elements,
and then retrieves the text of that element, assigning it to the variable:
*/
var thText = $(this).siblings('th').first().text();
console.log(thText);
});
JS Fiddle demo.
Or, using a little more DOM (a tiny, tiny efficiency increase):
// same as above:
$('tbody').on('click', 'td', function(){
/* using DOM (not jQuery), moving from the clicked 'td' element
to its parentNode ('tr'), retrieving the first of its children
(JavaScript is zero-indexed, the first child is at position '0'),
and retrieving its textContent (the text of the 'th'):
*/
var thText = this.parentNode.children[0].textContent;
console.log(thText);
});
JS Fiddle demo.
References:
first().
on().
siblings().
text().

This should work:
var index = $(this).index();
console.log($(this).parents("table").find("th:eq(" + index + ")").text());
Edit: row header: console.log($(this).closest("tr").find("th").text());
Fiddle: http://jsfiddle.net/wT3Ev/4/

You weren't too far off. This works with your example:
$(document).on("click", "#sTab td,#pvTab td", function () {
var tdIndex = $(this).index(),
table = $(this).closest('table'),
headingIndex = tdIndex + 1,
thText = table.find('th:nth-child(' + headingIndex + ')').text();
alert(thText);
});

$(this).parent().find('th').html();
edit: explanation - row is always cell's parent so no need to look for index - just look for header in the row where you have the cell.
http://jsfiddle.net/qA6R9/

Related

Scroll table row to top of div by clicking the row

Basically, I have a table that has many rows. What I want to do is scroll the row I click to the top of the div that encases the table.
Here is the StackOverflow question I started from:
How to scroll table to particular tr programmatically
Basically, this person was able to make the table jump to the table row he wanted by manually putting the in nth-child number like so:
var s = $("table tbody > tr:nth-child(20)").position();
$( "div" ).scrollTop( s.top );
Here is the fiddle he worked on showing it working for manually setting the nth-child in the code: http://jsfiddle.net/4Z7Z9/
Here is how I changed the code:
function scrollThisToTop(row) {
var s = $("table tbody > tr:nth-child(" + row + ")").position();
$( "div" ).scrollTop( s.top );
}
Here is my fiddle I am working on: http://jsfiddle.net/4Z7Z9/210/
Any help greatly appreciated!
I was able to get it working in 3 simple steps. Checkout the solution in fiddle HERE
You will need to add on click functionality as well as and ID for your containing div.
The new Function:
function scrollThisToTop(row) {
// Get the id of the row
var myElement = row.id;
// Get the variable for the top of the row
var topPos = row.offsetTop;
// The container div top to the row top
document.getElementById('container').scrollTop = topPos;
}
On click functionality:
$('tr').on("click", function () {
scrollThisToTop(this);
});
Div id:
<div id="container">
This helps you?
$('table tr').bind('click', function() {
var s = $('table').position();
$('div').scrollTop(s);
});

jQuery TableSorter - textExtraction based on external variable

I have a TableSorted table, and in each TD element are five SPAN elements. Four are always hidden, but upon clicking a div outside the table, certain spans are hidden dependent on which div is clicked.
I have the table sorting fine, but what I need is for the textExtraction to grab a different SPAN, depending on the value of the div which has been selected.
I've tried the following to no avail:
textExtraction:function(node){
var filter=$("div.career a.sel").text();
if(filter=="a"){var theindex=0;}
if(filter=="b"){var theindex=1;}
if(filter=="c"){var theindex=2;}
if(filter=="d"){var theindex=3;}
if(filter=="e"){var theindex=4;}
return $(node).find("span").eq(theindex).text();
}
What is the best way to achieve this?
The textExtraction function is only called when tablesorter is initialized or updated. Try triggering an update after the selection has changed.
var indexes = 'abcde'.split(''),
// Is this a select box?
$sel = $("div.career a.sel").on('change', function(){
$('table').trigger('update');
});
$('table').tablesorter({
textExtraction: function(node){
// if this is a select, get val(), not text()
var filter = $sel.val(),
theindex = $.inArray( filter, indexes );
return $(node).find("span").eq(theindex).text();
}
});
Update: for a link, try this:
var indexes = 'abcde'.split(''),
$careers = $("div.career a").on('click',function(){
var searcher = $(this).attr("rel");
$("div.career a").removeClass("sel");
$(this).addClass("sel");
$("td.stat span").hide();
$("td.stat span.career_" + searcher).show();
});
$('table').tablesorter({
textExtraction: function(node){
// find selected
var filter = $careers.filter('.sel').text(),
theindex = $.inArray( filter, indexes );
return $(node).find("span").eq(theindex).text();
}
});
Note: Don't use live() in jQuery version 1.9+, it was removed.

jQuery - Identify td that was clicked

I have created a grid (table) inside of an HTML doc based on user preference.
After appending the rows and cells to the table, it appears jQuery cannot access them properly? Its as if it doesn't consider them part of the DOM.
Essentially I will be handling everything inside of a multidimensional array for my data, such as:
[ ["","",""], ["","",""], ["","",""] ]
It is currently set up with appended rows named #row_0, #row_1, etc and td's added without an ID.
I need to be able to map the clicked TD to my jQuery so I can perform some functions and logic on it.
Is there any way to respond to my JS when a user clicks on a td with something like:
tr = [1]
td = [2]
Current code found here:
http://jsfiddle.net/HNjMR/4/
Here live example friend: http://jsfiddle.net/HNjMR/5/
$("#board").on('click', 'td', function(){
$("#board td").css("background","white");
$(this).css("background","red");
});
This happens because when you insert a new dynamic element on the page, ready jquery can not find it. The ready by default runs events only on existing elements at load time. While some functions like .on, solve this problem.
http://jsfiddle.net/898n2/1/
$( document ).on( "click", "td", function() {
alert(this.id);
});
This is using your current code
Notice I have used .on - this is a 'live' event using jquery
I have also modified your naming of each td to read col_1_2 - with 1 being col and 2 being row.
$("#row_"+i).append("<td id='col_"+j+"_"+i+"'> </td>");
when the td element click handler is added those target elements are not yet created so use event delegation and bind the click handler to the #board element with the target element selector as td as given below. Then use .index() to find the position of row and td(Add 1 to index as it is 0 based)
$("#board").on('click', 'td', function () {
var $td = $(this);
var td = $td.index() + 1,
row = $td.parent().index() + 1;
alert(td + '-' + row);
});
Demo: Fiddle
Also your create code is buggy, jQuery append does not work like string concatenation
$('#board tr').remove();
var size = parseInt($("#size").val());
for (var i = 0; i < size; i++) {
var $tr = $('<tr />', {
id: 'row_' + i
}).data('index', i + 1);
$("#board").append("<tr id='row_" + i + "'>");
for (var j = 0; j < size; j++) {
$('<td />', {
id: 'col_' + j
}).data('index', j + 1).appendTo($tr);
}
$("#board").append($tr);
}
Demo: Fiddle
Here the solution, remember that you should bind the eventclick when the elements was created, you souldn't use a generical $('td').click event, this does not work because some elements was not added in DOM yet.
$("#go").click(function(){
var size = $("#size").val();
if(size<3 || size>10){
alert("That is not a valid input. Please select 3-10");
return;
}
$('#board tr').remove();
// Check this bellow
var size = parseInt($("#size").val()),
tr = $("<tr/>"), td = $("<td/>"), tdc;
for(var i=0;i < size;i++){
for(var j=0;j<size;j++){
tdc = td.clone();
tdc.attr('id', 'col_'+j);
tr.append(tdc);
tdc.click(function(){
alert(this);
});
}
tr.attr('id','row_'+i);
$("#board").append(tr);
}
});

selector with table rows

I have an html table, and i add a class on one row.
The class is applied this way, and i later want to swap the rows.
$('.bTable').on('click', 'tbody tr', function(event) {
if($(this).attr('class')!='highlightgreen'){
$(this).addClass('highlightgreen').siblings().removeClass('highlightgreen');
}else{
$(this).removeClass('highlightgreen');
}
});
I cant seem to be able to select that class row with eq().
Error example: i try to alert() the a and the row appears fine, i alert() the b, and null comes up.
var a = $('.bTable tbody tr').eq(0);
var b = $('.bTable tbody tr .highlightgreen').eq(0);
How can i select properly that .highlightgreen row?
When selecting a TR with a class, you do $('tr.className'), notice there are no spaces.
When selecting an element inside a TR that has a class, you do $('tr .className').
So just remove the space
var b = $('.bTable tbody tr.highlightgreen').eq(0);
And eq(0) will get the first element in the collection
$('.bTable').on('click', 'tbody tr', function(event) {
$(this).toggleClass('highlightgreen')
.siblings().removeClass('highlightgreen');
});

Using JQuery to switch selected row of table

I have a table. When a row is clicked on, it is given .active and the row is highlighted. I need to work on other ways to change the selected row other than clicking on it. For my example, I've chosen a next button.
http://jsfiddle.net/dHxKW/
I can do the logic behind what happens when it gets to the end of the table or anything else like that.
I just need help figuring out how to get the index of the TR with class active so that I can increase the index, which then I can give the next row the active class... That's all I need to do... how to get that row index.
This is some of the stuff I've tried that doesn't work...
alert( $('table tr .active').index() );
var row = $('table tr.active').first();
alert(row.index() );
alert($("table").index( $('table tr .active') ));
This is what I'm using as a reference (https://stackoverflow.com/a/469910/623952)
var index = $("table tr").index($(this));
but I can't get the selectors right...
Solution.....
it would have never worked... I wrote bad code:
$(this).children("tr").addClass("active"); (this = clicked on tr in the click function)
But new code:
http://jsfiddle.net/dHxKW
$("#table_one").on("click", "tr", function () {
$(".active").removeClass("active");
$(this).children("td").addClass("active");
// removed line: $(this).children("tr").addClass("active");
$(this).addClass("active");
});
$('#btn_next').on('click', function ()
{
// right here **********
var n = $('tr.active').next();
$(".active").removeClass("active");
n.children("td").addClass("active");
n.addClass("active");
});
** Just as a note, I am adding the class to both the tr and td's... I'm not sure if this is the best way but tr doesn't have background properties, so I just added it to both. I think this might be the reason for my confusion....
The issue is that the "active" class is not being added to the "tr" elements.
In this line you are looking for tr children of this, but this is a tr, thus no children get selected: $(this).children("tr").addClass("active");
Instead try $(this).addClass("active");
var counter = 0;
var index = -1
$('table tr').each(function(){
if( ! $(this).hasClass('active')) {
counter++;
}
else index = counter;
})
$('td.active').parent().index('tr')
will get you the index.
jsFiddle example
jsFiddle example 2
BTW, the link in your click function $(this).children("tr").addClass("active"); would seem to do nothing as it searches for a child row of a row.
$('table tr .active').removeClass('active').parent().next().children('td').addClass('active');
this should do it

Categories

Resources