select the class of td - javascript

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

Related

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

create a variable from a class's other class

Trying to create a variable from a .class's second class.
var post_id = $('.divclass').hasClass('');
$(document).ready(function(){
$(post_id).click(function() {
$(this).fadeIn(1000);
});
});
I know this is wrong, but maybe someone here can help make sense of that I'm trying to do.
Thanks in advance.
So what you'll need to do is select the item with more than one class which you are doing:
var post_id = $('.divclass').attr('class');
//Now spilt the string by all of the spaces
post_id.split(" ");
//now refer to the string as an array
//lets get the second one.
post_id[1]
So for your case
//Added selector in this case a class with '.' this can be changed to be appropriate i.e '#' for an ID
$('.'+post_id[1]).click(function() {
$(this).fadeIn(1000);
});
Your post_id is a boolean. You are trying to attach an event handler to a boolean, when you should instead be attaching it to a DOM element. Don't use has class, but instead retrieve the class attribute:
var post_id = $('.divclass').attr('class');
post_id = post_id.replace('divclass', '');
If you're having 2 classes like below :
<div id="trash" class="a b">
<p>sample</p>
</div>
Then you can use jQuery selector is as below :
$(document).ready(function(){
$('.a.b').click(function() {
$(this).fadeIn(1000);
});
});
I hope this will help to you.

disable click event on first column

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() { ... });

jQuery toggle() text in separate element

I am having some trouble getting a toggle function to work and need someone to help explain it to me.
My HTML (simplified):
<div id="filter_names"></div>
<div class="item">Option 1</div>
<div class="item">Option 2</div>
<div class="item">Option 3</div>
<div class="item">Option 4</div>
My jQuery (simplified)
$(".item").click(function(){
var tagname = $(this).html();
$('#filter_names').append(' > '+tagname);
$(".loading").show();
});
As you can see I am appending clicked items' value to the div at the top. This works fine, but i need it to be removed when i click it again.
I am pretty sure it needs a toggle() function but so far my attempts have been pretty fruitless.
Some guidance would be greatly appreciated.
EDIT: You can see what i want to achieve in this JSfiddle. It's working exactly how i want it to by appending a value to the end (like a breadcrumb link), but is not being removed when i click it again.
You need to look at the #filter_names contents and check if the clicked tag's value is already included, then remove it if it is, or add it otherwise:
if (filternames.indexOf(tagname) === -1) {
$('#filter_names').append(' > '+tagname);
} else {
$('#filter_names').text(filternames.replace(' > '+tagname, ''));
}
Working fiddle: http://jsfiddle.net/passcod/Kz3vx/
Note that you might get weird results if one tag's value is contained in another's.
<script type="text/javascript">
$(function(){
$(".item").click(function(){
var $this=$(this);
var tagname = ' > ' +$this.html();
//if has item-check class remove tag from filter_names
if($this.hasClass("item-click")){
var h=$("#filter_names").text();
$("#filter_names").text(h.replace(tagname, '' ));
}
else{
$('#filter_names').append(tagname);
}
$(this).toggleClass("item-click").toggleClass("item");
});
});
</script>
try this one...
$(this).toggleClass("item-click item");
this will add these classes alternatively when you click on div. or if you just want to remove this class on second click then you should write this in your click handler.
if( $(this).hasClass("item-click")){
$(this).removeClass("item-click");
}
EDITED -----
to remove appended html you can try this...
if($(this).hasClass("item-click")){
$("#filter_names").text("");
}
else{
$('#filter_names').append(tagname);
}
it's working HERE
hope this helps you!!
I like passcod's solution - here's an alternative that wraps the elements in divs and puts them in alphabetical order.
JSFiddle here. The sort function is from http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/.
$(".item").click(function(){
var tagname = $(this).html();
var target = $('#filter_names').find('div:contains("> ' + tagname + '")');
if (target.is('*')) {
target.remove();
}
else $('#filter_names').append('<div class="appended"> > '+ tagname +'<div>');
function sortAlpha(a,b) {
return a.innerHTML > b.innerHTML ? 1 : -1;
}
$('#filter_names div').sort(sortAlpha).appendTo('#filter_names');
});

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