Javascript/Jquery: Cannot target Sibling Node in Table - javascript

I have a function that hides/shows a table by clicking on it's header which is contained in a <thead> tag. When clicked the table hides and all that is left is the header, which, by clicking again, can un-hide the table.
I have multiple tables and would like to only have to use on function, instead of writing one for each table. To do this I am trying to pass the arguments (this,this.lastSibling). For some reason this.lastSibling is not targeting any object. I've tried every way of navigating the node tree I can think of, but I cannot target the tbody.
My Javascript/Jquery
function ToggleTable(trigger,target){
$(trigger).click(function(){
$(target).toggle();
ToggleTable(trigger,target)
});
}
My HTML
<table class="format2" >
<thead onmouseover="ToggleTable(this,this.lastSibling)">
<!--Title-->
</thead>
<tbody>
<!--Cells with information in here-->
</tbody>
<!--Note No TFooter Tag-->
</table>
<--Other tables similar to the one above-->
Thanks in advance!

I have a function that hides/shows a table by clicking on it's header which is contained in a <thead> tag. When clicked the table hides and all that is left is the header, which, by clicking again, can un-hide the table.
I'm lost in your current code. But If you want to toggle the visibility of the tbody (or the last child element in your <table> tag you could try this.
function ready() {
$('table > thead')
.each(function(e){
$(this).siblings(':last').hide();
})
.click(function(e) {
$(this).siblings(':last').toggle();
});
}
$(ready);
Live sample: http://bl.ocks.org/3078240

If you would like to try a solution that utilizes core JavaScript instead of jQuery shims, this might work for you. It's a function I quickly wrote that returns the last sibling that is an HTML element (e.g. not a text node) although you should be able to easily modify it to accept any node in the DOM:
function getLastSibling(el) {
var siblings, x, sib;
siblings = el.parentNode.children;
x = siblings.length;
while ((sib = siblings[x - 1]) && x >= 0) {
console.log(sib);
console.log(sib.nodeType);
if (sib.nodeType != 1 || sib.tagName == 'SCRIPT') {
x--;
} else {
return sib;
}
}
return null;
}

Assuming all your tables will have the class format2 .
Try this:
$("table.format2 > thead").click(function(){
$(this).next("tbody").toggle();
});
JSFiddle: http://jsfiddle.net/KcY4X/

Related

Hiding container if all children are hidden in Angular

I am creating a number of tables dynamically, which all have a number of rows that are also created dynamically using Angular.
My goal is to have each table hidden if there are no visible rows in that table's tbody.
<table ng-repeat="package in listOfPackages" ng-if="this.getElementsByTagName('tbody')[0].childNodes.length > 0 ">
<tbody>
<tr ng-repeat="thing in package.things" ng-if="thing.status === 'interesting'">
<td>{{thing.someInfo}}</td>
<td>{{thing.someOtherInfo}}</td>
</tr>
</tbody>
</table>
The line ng-if="this.getElementsByTagName('tbody')[0].childNodes.length > 0" seems to be my problem - I do not know the proper way to find an element's own children, and check how many it has visible.
Is there any possible way to do this in angular?
create a function in your controller something like
$scope.showPackageTable = function (package) {
var toShow = false;
for (var thing in package.things) {
if (thing.status === 'interesting') { toShow = true; }
}
return toShow;
}
then you can use that in your html ng-if="showPackageTable(package)"

JQuery .parent click

The use of "this" and ".parent()" in jquery gets a bit confusing when it goes past simple divs or datatables. I have a table with the following structure: (I can't rename any of the classes or id)
<table class="table1">
<tbody>
<tr>
<div class="detail">
<table>
<thead></thead>
<tbody>
<tr>
<td>
<img class="picture_open" src="../location">
</td></tr></tbody></table></div></tr></tbody></table>
What I'm trying to do is have a click function on that img which will be able to grab the full RowElement.
What I have now:
$(".table1 tbody tr td img.picture_open").live('click', function () {
var overallTable = jQuery(this).parent("table").dataTable();
console.log("overallTable: " + overallTable);
var elementRow = this.parentNode.parentNode;
console.log("elementRow: " + elementRow);
var rowData = overallTable.fnGetData( elementRow );
console.log("rowData: " + rowData);
if ( this.src.match('img_name') )
{
//kills the table that was created if that row is opened
}
else
{
//runs ajax call to create another table since row is NOT opened
}
} );
However the code I have above prints out this:
overallTable: [object Object]
elementRow: [object HTMLTableRowElement]
TypeError: 'null' is not an object (evaluating 'oSettings.aoData')
In my problem is the $(this) incorrect? (Not getting the img with class "picture_open")
Or is my overallTable variable set up incorrectly with the .parent()?
Or is it my elementRow variable set up improperly with the parentNode?
Any help to clarify my errors would be amazing.
Thanks!
parent() in jQuery will parse only one level up the DOM, you should use .parents()/.closest(). This will fix your issue.
NOTE: .live() is turned into .on() in latest jQuery versions. Better to use .on()/.click()
parent() in jQuery only moves one level up the DOM, so what you probably want there is parents('table'). This should fix your overallTable issue.
in jQuery, .parent() only goes up the DOM once. What you should be using it .parents() to look up the DOM until it finds table
You need to use .closest('table') to find the closest table
Similary to find the element row
var elementRow = $(this).closest('tr');
Try this :
$('.table1').on('click', '.picture_open', function(ev) {
this // is .picture_open element
ev.target // is .picture_open element
ev.delegateTarget // is .table1 element
var $row = $(ev.delegateTarget).find('.detail tr').first();
});

Get Table Parent of an Element

I created dynamically a div with a class x in a table. How can I with JavaScript catch the table parent of this div and give it a certain class?
Passing through the tr and td parent Node didn't worked. Any ideas?
Assuming that no libraries are involved.
function getNearestTableAncestor(htmlElementNode) {
while (htmlElementNode) {
htmlElementNode = htmlElementNode.parentNode;
if (htmlElementNode.tagName.toLowerCase() === 'table') {
return htmlElementNode;
}
}
return undefined;
}
var table = getNearestTableAncestor(node);
if (table) {
table.className += ' certain';
}
If you have jQuery, this is very easy. If your HTML is something like this:
<table>
<tr><td><div class="mydiv">hi</div></td></tr>
</table>
Then you can say something like:
$('div.mydiv').closest('table').addClass('someclass');
The closest function goes up in the DOM tree until it reaches an element that matches the selector you give (in this case, table).
This is a relatively old answer, but now we have .closest which can traverse through elements until it finds the table:
var td = document.getElementById('myTdElement');
var table = td.closest('table');
if (table) {
table.className += ' certain';
}
Compatibility:
Assuming the new div's already inserted into the DOM tree, you can use jquery:
$(div_node).parents('table')[0].addClass('certain_class');
Bare javascript can do similar things, but you'll have to write a loop to iterate up each .parentNode, test if it's a table, etc...
Using jQuery If your HTML is something like this:
<table>
<tr><td><div class="divClass">Content</div></td></tr>
</table>
Then you can call parent table like:
$('div.divClass').parent();
below code will give html of your table:
alert($('div.divClass').parent().html());
You can use $('div.divClass').parent(); as you want ...
Cheers!

jQuery change all tr classes after specified one

I have a data table with alternating row background colors. I have an AJAX script to delete a row. I can't come up with a way to change the class of all the rows beneath the one that was deleted so that it alternates correctly again.
For example, considering the following:
`<tr id="1" class="row1">
<td>blah</td>
</tr>
<tr id="2" class="row2">
<td>blah</td>
</tr>
<tr id="3" class="row1">
<td>blah</td>
</tr>
<tr id="4" class="row2">
<td>blah</td>
</tr>`
Now, using my AJAX script, I remove id2, then id3 will move underneath id1 and they will have the same row color. I managed to make my script change the next tr class, but that doesn't really help because then it's just the same color as the one after that. I can't figure out how to iterate through all of the next tr's, and change their class accordingly.
What I have so far:
$('#news_' + id).fadeOut('slow');
var currtr = $('#news_' + id).attr('class');
var nexttr = $('#news_' + id).closest('tr').next('tr').attr('id');
$('#' + nexttr).removeClass($('#' + nexttr).attr('class'));
$('#' + nexttr).addClass(currtr);
You could just iterate over the visible<tr> elements, and remove the class from the even ones, and apply to the odd ones.
Something like this:
Example: http://jsfiddle.net/2CZdT/
$('tr:odd').addClass('odd');
$('td').click(function() {
$(this).parent().fadeOut(function() {
$(this).siblings('tr:visible').filter(':even').removeClass('odd')
.end().filter(':odd').addClass('odd');
});
});​
I have the click event on the <td>, so when one is clicked, it traverses up to the parent <tr> element, fades it out, the in the callback, it grabs all visible sibling <tr> elements, filters the even ones, removes the .odd class, then goes back and filters the odd ones, and adds the .odd class.
Note that this presumes there's a default class applied in your CSS, then you override the odd ones (or even ones) with the alternating class.
Easiest way is to go over the whole table again, e.g. add this after the fadeOut:
$('#id_of_your_table tr:even').addClass('even');
Edit: on second thought, that won't work since the row you faded still exists, but just isn't visible. You need to remove it from the DOM, or skip it when re-applying the zebra-effect. Example:
$('#news_' + id)
.fadeOut('slow')
.remove()
.closest('table')
.find('tr:even').addClass('even');
Or:
$('#news_' + id)
.fadeOut('slow')
.addClass('skip')
.closest('table')
.find('tr:not(.skip):even').addClass('even');
You can also target the table directly as in the first example, but you might as well move up from the faded row to the table its in.
You could use the next siblings selector to get all the rows following the one you are going to delete. Delete the desired row. Then, you should already have the following siblings, so just .each() them and change their class.
E.g.
var followingRows = $("#id2 ~ tr");
$("#id2").remove();
followingRows.each(function() {
if (this.is('.even')
this.removeClass('even').addClass('odd');
else
this.removeClass('odd').addClass('even');
});
Something close to that...
Let CSS do the work for you.
table tr:nth-child(2n+1) {
background-color: #eef;
}
no JavaScript required! =)
I would do something like this:
$('news_' + id).fadeOut('slow', function() {
$(this).remove();
});
var i = 1;
$('tr').removeClass().each(function() {
if (i == 1) {
$(this).addClass('row' + i);
i++;
} else {
$(this).addClass('row' + i);
i--;
}
});

How to do this in jQuery?

I have to attach the method copyToLeft on onClick event of all images which are inside the TD. TD is inside the table named mismatchList, so that the structure becomes like this mismatchList > tbody > tr > td > img
Although i have already done this, but that is using plain javascript. What i did was, i manually added copyToLeft(this); method on onClick event of all specified elements at the time of creation. [ This is the step which i want to omit and use jQuery to do this somehow ].
Also definition of copyToLeft goes like this:-
function copyToLeft(obj){
leftObj = getLeftTD (obj); // my method which returns the adjacent Left TD
rightObj = getRightTD (obj);
if ( leftObj.innerHTML != rightObj.innerHTML ) {
leftObj.innerHTML = rightObj.innerHTML;
leftObj.bgColor = '#1DD50F';
}else{
alert ( 'Both values are same' );
}
}
If required copyToLeft method's definition can also be changed. [ just in case you think, jQuery can be used to make this method better :) ]
Edit
Instead of asking another question i am just adding the new requirement :) [ let me know if i am supposed to create new one ]
i have to add copyToLeft method to all images as i specified, but alongwith that image src should be left_arrow.gif, and add copyToRight method if src is right_arrow.gif. Also, how can we get the adjacent left/right TD in jQuery, as i want to replpace my getLeftTD and getRightTD method as well?
If i've understood your question correctly, in jQuery, you'd bind the event as such:
$(document).ready(function() {
$('mismatchList > tbody > tr > td > img').click(copyToLeft);
});
In your copyToLeft function, you don't accept obj as an input parameter, instead this will be the image. $(this) will be a jQuery object, containing the image, should you require it...
You could do something like this to match the image src.
$('#mismatchList > tbody > tr > td > img[src='left_arrow.gif']').click(copyToLeft);
$('#mismatchList > tbody > tr > td > img[src='right_arrow.gif']').click(copyToRight);
It is worth noting that the part matching the image src does use the entire contents of src, so if you move the images to a different directory it will stop working. If you just want to match the end of source you can use $= instead of just =.
Here's a variation on TheVillageIdiots rewrite of your copy left function.
function copyToLeft() {
var cell = $(this).closest('td');
var leftObj = cell.prev();
var rightObj = cell.next();
if ( leftObj.html() != rightObj.html()) {
leftObj.html(rightObj.html());
leftObj.css('background-color','#1DD50F');
} else {
alert ( 'Both values are same' );
}
}
Part of me also thinks it would make sense to just have one copyToSibling function where you check $(this).attr('src') for whether it's left_arrow.gif or right_arrow.gif and act accordingly, rather than the two selectors I posted before.
try this code:
<table id="tbl">
<tbody>
<tr>
<td></td><td><img src="file:///...\delete.png" /></td>
</tr>
<tr>
<td></td><td><img src="file:///...\ok.png" /></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function(){
$("table#tbl img").click(function(){
var td=$(this).parents("td");
var tr=$(td).parents("tr");
var left=$(td).prev("td");
$(left).html($(td).html());
});
});
</script>

Categories

Resources