Use case:
user clicks on a datatable cell. Depending on the row and column of that cell certain action should be executed.
How can I check whether that doesn't click on a certain column and if he does not click on that column, then I would retrieve information from the row he clicked on and allow him to execute an action based on that information.
I did it like this and it works:
var validColumn = false;
$('#fooTable tbody').on( 'click', 'td', function () {
validColumn = $('#fooTable').DataTable().cell(this).index().column !== 5;
});
$('#fooTable tbody').on('click', 'tr', function () {
if (validColumn) {
//do stuff
}
});
But I feel there is a more elegant approach.
First set an aria to the td to identify the position, something like
Table wiht 6 columns so
<tr aria-number="1">
<td aria-number="1">
<td aria-number="2">
<td aria-number="3">
<td aria-number="4">
<td aria-number="5">
<td aria-number="6">
</tr>
Same for tr, think is easy way to do
Use jQuery function .parent(), sending $(this), so.
var td = $(this).parent();//If the item clicked is something inside of td
var tr = $(this).parent().parent();//To select the tr where was clicked
And call the aria with
if(td.attr('aria-number') == 6){ //do something; }
Related
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>
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;}
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.
<tbody>
<tr>
<td>Name1</td>
<td>Position1</td>
<td>Operation1</td>
</tr>
<tr>
<td>Name2</td>
<td>Position2</td>
<td>Operation2</td>
</tr>
</tbody>
I need to get the string in the first <td> when I click the last <td> inside the same <tr>,
for example, if I click in the <td> contains "Operation1", I could get a string with the value "Name1".
How to do this? (In reality, the strings among different <td>s have not any relationship, like the same postfix here)
Oh, BTW, this table is created by using jQuery Datatables plug-in.
Thanks a lot!
There are multiple ways to do it, such as:
$('td').parent().children().filter('td:first');
$('td').parent('tr').find('td:first');
$('td').siblings('td:first');
Here's a jsFiddle example.
Use this :
$(document).on('click', 'td:last', function(){
$(this).siblings(':first')
})
Here is a Javascript only solution for a static page, this attaches an event listener to the tr and intercepts the click events of its children. the contents of the tr can be dynamic.
Array.prototype.forEach.call(document.getElementsByTagName("table"), function (table) {
Array.prototype.forEach.call(table.getElementsByTagName("tr"), function (tr) {
tr.addEventListener("click", function (evt) {
var children = this.children,
length = children.length;
if (length && children[length - 1] === evt.target) {
alert(children[0].firstChild.nodeValue);
}
}, false);
});
});
On jsfiddle
Which in jquery terms would be
$("table tr").on("click", function (evt) {
var target = $(evt.target);
if (target.parent().children().last().get(0) === evt.target) {
alert(target.parent().children().first().text());
}
});
On jsfiddle
Or rather than set an event listener per tr element ("bubbling"), you could also use event "bubbling" and move it all the way out to document (what those at jquery call Event Delegation, jquery.on), this will allow for quite a dynamic system if you add and remove rows from your table, or even whole tables.
document.addEventListener("click", function (evt) {
var target = evt.target;
if (target.nodeName === "TD" && target.parentNode.children[target.parentNode.children.length - 1] === target) {
alert(target.parentNode.children[0].firstChild.nodeValue);
}
}, false);
On jsfiddle
Or using jquery delegation
$(document).on("click", "td", function (evt) {
var target = $(evt.target);
if (target.parent().children().last().get(0) === evt.target) {
alert(target.siblings().first().text());
}
});
On jsfiddle
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>