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();
});
Related
I want to select the class of the td that is clicked inside my table and then pass it to a function.
<table>
<tr>
<td class = "Vespalx">Vespa lx</td>
</tr>
</table
So in jQuery I tried to select it whit:
$type = $(this).closest("table").find("div");
then I want to perform an action on $type:
$type.click(function(){
$("body").hide();
}):
But now nothing happens!
Did I make a fault with selecting the div?
Is this helping ?
$('td').click(function(){
$(this).attr('class');
// or
$this.classList;
});
You are searching for a div. There isn't any div in your sample code.
I adapted your piece of javascript to find the td.
$type = $(this).closest("table").find("td");
alternatively you could use the css class selector (Vespalx) also.
You need to clarify what is $(this) in your code. However this is a solution:
$type = $("body").find("table").find("td");
$type.click(function(){
$("body").hide();
});
I replaced $(this) with $("body") and I used find method to get the table instead of closest that doesn't work for me. Then I fix the error of second find. In your second find you search for a div and not for a td. At the end of your code I see : and this is wrong. You must use ; and not :
Tnx for all the answers!!!
Know I see that my question was a vague.
But what I wanted was select the class of the td that is clicked and then do something with this class.
See my code:
function scooter (klas) {
var clas = $(klas);
clas.addClass("allscootervis");
//$(".allscooter").css("display", "block");
//$scooter = $("div > this", ".ScooterContent");
$(".introduction").replaceWith("");
}
$("td").click(function(){
$typeun = $(this).attr('class');
//$type = '$(".' + $typeun + '")';
$type = '.' + $typeun;
scooter($type);
});
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/
Can someone help me how to disable the click event on first column and the other columns should be clickable. I have tried several different ways like slice
td.slice() after tr element and also td:gt(0)
etc and was unsuccessful. I had been banging my head since 2 days and I didn't find any relevant solutions out on google.
$('#Table tbody tr').on("click",function(){
var aPos Table.fnGetPosition(this);
var aData = Table.fnGetData( aPos[6] );
//aData = $(this).parent().parent().html();
xyz = $(this).parent().parent().find("td").eq(1).html();
yzx= $(this).parent().parent().find("td").eq(7).html();
zxy= $(this).parent().parent().find("td").eq(2).html();
alert(aPos);
});
Try stopPropogation on first column click DEMO
Edit: Added demo and fixed .find('td:first')
$('#Table tr').find('td:first').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
});
add some kind of unique identifier on the first column and
$('identifier').click(function(){
return false;
});
I think you can also target first column with the n-th child thing but I am not sure of the exact syntax. Maybe something like
$('table tr td:(nth-child(1)').on('click', function(){
return false;
});
or something like the above, hope it helps
You need to add some kind of identifier to the columns you want to use:
<tr>
<td class="dontClickMe"></td>
<td class="clickMe"></td>
</tr>
Then it's as simple as:
$('.clickMe').on('click', function() { ... });
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!
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>