Finding the td associated to its table onclick event - javascript

I have a table like below
<table onclick="dosomething()">
<tr><td>11</td><td>12</td><td>13</td></tr>
<tr><td>11</td><td>12</td><td>13</td></tr>
<tr><td>11</td><td>12</td><td>13</td></tr>
</table>
After I click on the table, I need to find the td on which the click happened. I cannot have onclick event written on tr or td.

You can do something like this (give your table a class of myClass- or whatever you want):
function tableClicked(td) {
// Do something dependent on the td which was clicked
}
$(document).ready(function () {
$("table.myClass td").click(function () {
tableClicked(this);
});
});
This means that you don't have to add onclick attributes to the <td> tags.

Add an Id to the table and remove onClick handler. this is to seperate the behavior and content.
<table id="tableId">
since event will bubble up, capture it on table element and find the target, so you don't need to add event listener to every td.
$('#tableId').click(function(e){
//the td is the target where event happens
var td=e.target;
});

$(function(){
$("#tbl").bind("click", function(e){
if(e.target.tagName == "TD"){
//do your magic
}
});
});

I would dump the onclick and do this
$("#myTable td").click(function() {
$(this).html(); // get the value
$(this).hide(); // hide it
$(this).remove(); // remove it
});
<table id="myTable">
<tr><td>11</td><td>12</td><td>13</td></tr>
<tr><td>11</td><td>12</td><td>13</td></tr>
<tr><td>11</td><td>12</td><td>13</td></tr>
</table>

Related

Get value of Table Row with mouse click? (JQuery)

I have a table, where I display some data. Every table row has a ID. This ID is the value of every tr-tag. When I click a row of the table, I want to display the ID in the console.
Table:
$.getJSON(`http://localhost:5000/Flights/Flights/${fromAirport}/${toAirport}`)
.then(data => {
console.log(data);
$('#flights').find("tr:gt(0)").fadeOut().empty();
for (let item of data) {
console.log('entered loop');
$(`<tr value="${item.flightId}">`).appendTo('#flights')
.append($('<td>').html(item.date))
.append($('<td>').html(item.departureTime))
.append($('<td>').html(item.arrivalTime))
.append($('<td>').html(item.flightNr))
.append($('<td>').html(item.price))
.append($('<td>').html(item.airplane))
.append($('<td>').html(item.nrSeats))
.append($('<td>').html(item.nrVacant))
.append($('<td>').html(item.nrBooked))
.append($('<td>').html(item.flightId))
}
});
On Click Method:
$('#flights').on('click', function (e) {
const entry = $(e.target.val());
console.log(entry);
});
This on click event is not working, but I do not really know why. Maybe someone has a idea :)
Do you mean this?
When the user clicks on a tr, it receives the value
$('tr').on('click',function(){
value = $(this).attr('value');
console.log(value);
})
There are a couple of errors here:
The target of the click is the table itself, you have to select the
tr.
A syntax error: .val() is a jQuery function, you can't use it
on the target, you have to close the parens before: $(e.target).val().
Even then .val() is used for inputs, for this you have to access the attribute directly.
All together, using event delegation, you can do the following:
$('#flights').on('click', 'tr', function() {
console.log($(this).attr('value'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="flights">
<tr value="1">
<td>Item1</td>
</tr>
<tr value="2">
<td>Item1</td>
</tr>
</table>

Disable on-click event for single column

Can anyone let me know how to disable on click event for particular column.
Scenario : We displayed user details in a table , once click has been made on the table row, popup dialog window will appears with more details(Calling ajax request to retrieve details from database) . But our constraint is to disable on click event for single column associated with the table.
Eg :
<table border = '1'>
<tr>
<th> Name </th>
<th> Id </th>
<th> Phone Number</th>
</tr>
<tr onclick = "testing()">
<td> Krupa </td>
<td> 123 </td>
<td id = "disableClick"> <a href = "http://www.google.com" target= '_blank'>Click me </a> </td>
</tr>
</table>
If click has been made on text(1st and 2nd column) , it will invoke on click event . But if user clicks on hyper link (3rd column) , i want to redirecting it to Google but not on-click event(testing()).
Can anyone help me to achieve this .
try:
$(function() {
$('table td').on('click', function() {
if ($(this).index() == 2) {
return false; // disable 3rd column
}
});
$('table tr').on('click', function() {
alert('You click the row');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>1</td><td>2</td><td>3</td></tr>
</table>
do this through CSS
table td:nth-child(2) {
pointer-events: none;
}
How about adding your click events to the column, then removing the event once it has been clicked using .unbind(). This will remove the event of the column that was clicked, but any others should still work.
$( '.column' ).on( 'click', function()
{
// do ajax stuff...
// remove event
$( this ).unbind();
});
If you only want the click event to run once, you theoretically could use jquery's .one() feature instead of .on(). This will automatically unbind the event after running once. Of course this would mean you would have to bind the event again afterwards (if you need it)
http://api.jquery.com/one/
For example
$('.selector').one('click', function(){
// your callback functionality
});
Another thing you could do would be to somehow check if the popup is active, and prevent the click handler from running if so
For example
$('.selector').on('click', function(){
if (check_if_popup_is_active) {
return;
}
// otherwise continue with
// your callback functionality
});
You can use the jQuery .unbind() function from within your callback.
Consider following table for instance
<table>
<tr>
<th class='foo'>bar</th>
</tr>
</table>
We can stop onclick events on th.foo as following
$('th').on('click', '.foo', function() {
var that = this;
// your AJAX call goes here
success: function() {
$(that).unbind('click');
}
});
You can do this via CSS
you_css_selector {pointer-events:none;}

Get the value from a particular column

I'm trying to alert message on click each column. I have a table in which three row and four column, now I want alert message with next column value on third column click of each table. I have tried this but all column get value not a particular column. my problem is this is invoke in every column click but I want alert message only when third column click of each row.
HTML
<table id='myTable'>
<tr><td>R1C1</td><td>R1C2</td><td>R1C3</td><td>R1C4</td></tr>
<tr><td>R2C1</td><td>R2C2</td><td>R2C3</td><td>R2C4</td></tr>
<tr><td>R3C1</td><td>R3C2</td><td>R3C3</td><td>R3C4</td></tr>
</table>
JS
$("#myTable tr").bind("click", function () {
alert($(this).children("td").eq(3).html());
});
Demo Here
please try this code
$(document).ready(function () {
$('#myTable tr').each(function (Mindex, Mval) {
$(Mval).find('td:eq(2)').click(function () {
alert($(Mval).find('td:eq(3)').html());
});
});
Try this
$('table#myTable tr td:nth-child(3)').on('click', function() {
alert($(this).next().html());
});
Check Here
$("#myTable tr td:nth-child(3)").click(function () {
alert($(this).next().html());
});
Try this:
$('#myTable').children('tr').children('td').eq(3).on('click', function() {
alert($(this).next().html());
});
The above function makes sure that you are calling the direct children elements but not any nested other same elements. Solves future regressions.
If your table is going to stay the same size there are answers that already work. If your table is going to grow I would recommend doing some event delegation. It will dramatically speed up the page if there are going to be a large number of event listeners.
$('#myTable').on('click', 'td:nth-child(3)', function(){
alert($(this).text());
});
See this jsfiddle, and this jquery documentation.
below code will find and set the desired column value
$('#myTable tr:gt(0)').each(function(){
// console.log($('td:eq(3)', $(this)).html());
alert($('td:eq(3)', $(this)).html());
$('#myTable').find('tr:gt(0)').find('td:eq(3)').html("hello");
});
Try this:
var thirdEle = $("#myTable tr td:nth-child(3)");
thirdEle.bind("click", function () {
alert($(this).html());
});

jquery trigger table row click event

Sample Code:
<table class="grid">
<tr>
<td>click me </td>
<td class="unitNumber"><span>Unit 1</span></td>
<td class="unitStatus">Open</td>
</tr><tr>
<td class="unitNumber"><span>Unit 2</span></td>
<td class="unitStatus">Sold</td>
</tr>
</table>
I am able to get the row index of the row selected to get the exact column data.
tr = $('.grid').find('tr');
tr.bind('click', function(event) {
unitNo = $(this).find("td.unitNumber span").html();
alert(unitNo);
});
The above tr click event is fine.
My problem now is how to trigger this tr binding event when clicking the anchor link <td>Show map </td>within the table row?
Goal:
To get first the unitNo (processed on tr.bind click event) before processing the rest of the code on anchored link?
I tried to duplicate the tr click function within the anchor link click event but got undefined value on unitNo. See my code:
$('a[id^="unit_floor_plan_preview"]').bind('click',function() {
var tr = $('.grid').find('tr');
unitNo = $(this).find("td.unitNumber span").html();
alert('From link: ' + unitNo);
});
test code:
http://jsfiddle.net/VjkML/29/
Change:
unitNo = tr.find("td.unitNumber span").html();
To:
unitNo = $(this).find("td.unitNumber span").html();
In $('a[id^="unit_floor_plan_preview"]').bind('click' You try to find "td.unitNumber span" within $(this). The problem is, this refers to the link clicked on, thus you'll never find anything!
FYI, you could easily rewrite that ENTIRE statement as follows:
$(document).on("click", '.grid tr, a[id^="unit_floor_plan_preview"]', function(e) {
e.stopPropagation(); // will prevent double click events from link being clicked within row
var unitNo = $.trim($(this).closest("tr").find(".unitNumber span").text()); // trim to remove end space, closest gets closest parent of selected type
if (e.target.tagName == "A") alert('From link: ' + unitNo);
else alert(unitNo);
});
Example
The best way is to bind the event only to your tr and use the event.target to check if it is tr or any other element that was clicked. This way your click event will not be duplicated.
This should work
var unitNo;
var tr;
tr = $('.grid').find('tr');
tr.bind('click', function (event) {
if ($(event.target).is('tr')) {
// If it is a tr that is clicked then just use find
unitNo = $(this).find("td.unitNumber span").html();
} else {
// If not tr find the closest tr and then find the element
unitNo = $(this).closest('tr').find("td.unitNumber span").html();
}
alert(unitNo);
});
Check Fiddle
Try:
var unitNo;
var tr = $('.grid').find('tr');
$('a[id^="unit_floor_plan_preview"]').on('click',function(e) {
e.stopPropagation();
unitNo = $(this).closest('tr').find("td.unitNumber span").html();
alert('From link: ' + unitNo);
});
tr.on('click', function(event) {
unitNo = $(this).find("td.unitNumber span").html();
alert(unitNo);
});
jsFiddle example
With the link you need to go up the DOM to the row (via .closest()), then use .find() to go back down the same row to find the span you want to get the Unit value.

How can I add a "selected" class to just one row of a table when a row is clicked?

I am using the following code:
$("#dataTable tbody").on("click", "tr", function (event) {
if (!$(this).hasClass('row_selected')) {
$(oTable.fnSettings().aoData).each(function () {
$(this.nTr).removeClass('row_selected');
});
$(this).addClass('row_selected');
gridClickHandler($(this));
}
});
When a row is clicked then if the row is already selected nothing happens. If not then all the rows have the class removed and the current row has the row_selected class added.
However this is slow as my tables have many rows. It does not look good with the current delay. What I thought of was moving the addClass to the start. But if I do that the the .each loop removes it.
Is there a way I could make this work more efficiently (faster response)?
<table id-"dataTable">
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
Here's a sample
$('table').on('click', 'tr', function() {
var row = $(this); //cache the row
if(!row.hasClass('selected'){
row.addClass('selected') //add class to clicked row
.siblings() //get the other rows
.removeClass('selected'); //remove their classes
gridClickHandler(row);
}
});​
The advantage of using .on() is that it binds only one event handler to the parent (in this case, table) for the children (the tr). Using .click() on each row means there is one handler for each tr element which is an overhead.
So for example, if I had a thousand rows, there would be a thousand click handlers when you use .click() as opposed to only click handler on the table to listen for all the tr's click events when using .on().
Try this:-
$("#dataTable tbody tr").on("click", "tr", function (event) {
$("#dataTable tbody tr").removeClass('row_selected');
$(this).addClass('row_selected');
}
});
$("#dataTable tbody tr").click(function () {
$('#dataTable tbody tr.selected').removeClass('selected');
$(this).addClass('selected');
gridClickHandler($(this));
});
Check this jsfiddle, works quite fast even with big tables!
-- edited after comment --
$("#dataTable").on("click", "tr", function (e) {
var $this = $(this);
// this line removes all selected classes from the rows siblings
$this.siblings().removeClass("row_selected");
// this line will toggle the selected class,
// therefore deselecting the row if it has been selected before
$this.toggleClass("row_selected");
gridClickHandler($this);
});
Or alternatively cache the previously selected row.
(function() {
var $oldSelected = null;
$("#dataTable").on("click", "tr", function (e) {
var $this = $(this);
// this line removes all selected classes from the rows siblings
$oldSelected.removeClass("row_selected");
// this line will toggle the selected class,
// therefore deselecting the row if it has been selected before
$oldSelected = $this.addClass("row_selected");
gridClickHandler($this);
});
})();
And as a side note, caching jQuery calls - or result of a function call that you need repeatedly for that matter - is always a good idea to save on processing time.

Categories

Resources