how to get the td clicked having tr - javascript

I have a tr with a click listener. I want to know which td was the one clicked:
<tr class ="clickingClass">
<td> first td </td>
<td> second td </td>
</tr>
$(".clickingClass").on('click', function() {
$(this).closest('td');
});
The above shows nothing. How can I do this?

The issue is because closest() goes up the DOM, not down it.
To do what you require you could instead attach the event handler directly on the td elements:
$(".clickingClass td").on('click', function() {
// do something with $(this)...
});
Alternatively you could use the target property of the event passed to the handler function to determine which td was clicked:
$(".clickingClass").on('click', function(e) {
// do something with $(e.target)...
});

You can use event.target for this
$(".clickingClass").on('click',function(event){
alert(event.target);
});

Why not bind to the tds instead?
$(".clickingClass td").on('click',function(){
this //td
});

Related

onclick i want to get the tr element but it gives me td element

I have a table and when i click on a tr element the function gives me td element. Why is that?
let func = function () {
$("tr").on("click", (event)=> {
event.preventDefault();
event.stopPropagation();
console.log(event.isPropagationStopped()); // true
let targetEl = $(event.target);
console.log(targetEl); // Object [ td ]
});
};
func();
I want "onclick" to give me the tr and don't know where is the problem.
Can someone help me?
currentTarget or closest()
$("tr").on("click", (event) => {
event.preventDefault();
event.stopPropagation();
console.log('target:', event.target.tagName)
console.log('target closest:', event.target.closest('tr').tagName)
console.log('currentTarget:', event.currentTarget.tagName)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
</table>
This is just because you stopped the event propagation. Hence the click event wasn't transferred to the parent element. The default event propagation in JavaScript is the bubbling method. Read this article for better understanding

The jquery selector always selecting even it should not

$("#question-proper table tr td input[value='Save']").on('click',function(){
var number = parseInt($(this).attr('data'));
$(this).attr("value","Add");
alert("Clicked");
});
When i click again the input button with the value of Add. It alerts again as not expected. It should not because the value now of input button is "Add" not the "Save".
$(document).on("click", "input[value='Save']", function(){
$(this).attr("value", "Add");
alert("clicked");
});
adapt this to fit your needs
Fiddle here: http://jsfiddle.net/omofa2v9/
Read about event delegation here
The event is bound to the element and is kept even if it no longer match the query. In fact, the event don't even know what the query was, only the actual elements it was added to.
Possible solutions:
Delegate to a parent element:
$("#question-proper table tr td").on('click', "input[value='Save']", function(){
var number = parseInt($(this).attr('data'));
$(this).attr("value","Add");
alert("Clicked");
});
Check in the event:
$("#question-proper table tr td input[value='Save']").on('click',function(){
if($this).attr('value') !== 'Save') return;
var number = parseInt($(this).attr('data'));
$(this).attr("value","Add");
alert("Clicked");
});
Run the event only once by using .one:
$("#question-proper table tr td input[value='Save']").one('click',function(){
var number = parseInt($(this).attr('data'));
$(this).attr("value","Add");
alert("Clicked");
});

Separate click event for first three td and last td not working in Dom change

I am having four column in my table. When we click one of the first three td that will do one operation and when we click last td that will do other kind of operation.
I did like this
$('#items_list tr td').not('#items_list tr td:last-child').click(function() {
// Do something
}
$("#items_list tr td:last-child").click(function() {
// Do something
}
But those not working when Dom change. I try to use .live(), but the disadvantage of li is
Chaining methods is not supported. Any one can guide me?
There is no need to add events to every cell on the table. One event handler at the table tbody level can handle it.
jQuery("#foo tbody").on("click", function (evt) {
var elem = jQuery( evt.srcElement || evt.target );
if (elem.is("td:last-child")) {
alert("last child");
} else {
alert("not last child");
}
});
You might have to add code to the elem to look for the closest td if you have elements inside of the td.
if (!elem.is("td")) {
elem = elem.closest("td");
}
jsFiddle
$("#items_list tr td").last().click(function(){ });

jQuery - Click event on <tr> elements with in a table and getting <td> element values

I have the following HTML in a JSP file:
<div class="custList">
<table class="dataGrid">
<c:forEach var="cust" items="${custList}">
<tr>
<td>${cust.number}</td>
<td>${cust.description}</td>
<td>${cust.type}</td>
<td>${cust.status}</td>
</tr>
</c:forEach>
</table>
</div>
I need to be able to trigger a 'click' event on each of the dynamically created <tr> tags and also be able to access the values of the <td> tags (of the clicked <tr>) from within the JavaScript function. I have this function already, but sadly it doesn't seem to be working.
$(document).ready(function() {
$("div.custList > table > tr").live('click', function() {
alert("You clicked my <tr>!");
//get <td> element values here!!??
});
});
Update (Jan 2016): jQuery.live is deprecated (as noted here:http://api.jquery.com/live/)
As of jQuery 1.7, the .live() method is deprecated. Use .on() to
attach event handlers.
Unless otherwise definied (<tfoot>, <thead>), browsers put <tr> implicitly in a <tbody>.
You need to put a > tbody in between > table and > tr:
$("div.custList > table > tbody > tr")
Alternatively, you can also be less strict in selecting the rows (the > denotes the immediate child):
$("div.custList table tr")
That said, you can get the immediate <td> children there by $(this).children('td').
Try jQuery's delegate() function, like so:
$(document).ready(function(){
$("div.custList table").delegate('tr', 'click', function() {
alert("You clicked my <tr>!");
//get <td> element values here!!??
});
});
A delegate works in the same way as live() except that live() cannot be applied to chained items, whereas delegate() allows you to specify an element within an element to act on.
This work for me!
$(document).ready(function() {
$(document).on("click", "#tableId tbody tr", function() {
//some think
});
});
Since TR elements wrap the TD elements, what you're actually clicking is the TD (it then bubbles up to the TR) so you can simplify your selector. Getting the values is easier this way too, the clicked TD is this, the TR that wraps it is this.parent
Change your javascript code to the following:
$(document).ready(function() {
$(".dataGrid td").click(function() {
alert("You clicked my <td>!" + $(this).html() +
"My TR is:" + $(this).parent("tr").html());
//get <td> element values here!!??
});
});​
$("body").on("click", "#tableid tr", function () {
debugger
alert($(this).text());
});
$("body").on("click", "#tableid td", function () {
debugger
alert($(this).text());
});
$(this).find('td') will give you an array of td's in the tr.
<script>
jQuery(document).ready(function() {
jQuery("tr").click(function(){
alert("Click! "+ jQuery(this).find('td').html());
});
});
</script>

jQuery: Selecting an element in inside an already selected element

For example:
$("table tr").click( function(event)
{
//Say, here i want get the data of td element where its class name="special"
});
Is there any way I can select a element while in the click event, a element under the attached element above $("table tr")?
In this specific case, you can do this:
$("table tr").click( function(event)
{
$(this).children('td.special').whatEverYouNeed();
});
Generally speaking, you need to use find():
$("table tr").click( function(event)
{
$(this).find('td.special').whatEverYouNeed();
});
Something like
$(this).find(".special").html();
I think that that works

Categories