how to catch the table data td value? - javascript

How to catch the td value in jquery on mouse click event? I have done these things in pure js but it is lengthy. Can jquery have easy solution? I want to add those catch value in the form text field.

$("#theTable").click(function(e) {
var data = $(e.target).closest("td").text();
});

<script type="text/javascript">
$(document).ready(function(){
$("#myTable td").click(function(){
alert($(this).html());
})
})
</script>
<table id="myTable" border="1" >
<tr>
<td>value 1</td>
<td>value 2</td>
<td>value 3</td>
</tr>
</table>

You can use .delegate(). One handler on the container element (table) manages events on all the contained elements (filtered to your preference, e.g. "td"):
$('#thetable').delegate('td','click', function(){
alert('Value is ' + $(this).text() );
});

Related

Checking for last double clicked element with jQuery

Is there a way to check for the last double clicked element with jQuery. I've made
a table and I want to know how to identify the most recent double clicked <td></td> in my code. I tired something like this:
var clickedTD = $("td").dblclick;
But It didn't work.
element.dblclick() should work provided the DOM is loaded... See the example below...
$(document).ready(function() {
//set up dblclick event on the table data elements
$("td").dblclick(function(){
//$(this) use key word this for the element clicked
$("#display").text(`You double clicked: ${$(this).text()}`)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>Click 1</td>
<td>Click 2</td>
<td>Click 3</td>
<td>Click 4</td>
</tr>
</table>
<div id="display"></div>
I don't really think jQuery is necessary for this:
<td>onclick="checkClick(this)"></td>
function checkClick(clickedElement) {
var clickCount= clickCount + 1;
if(clickCount === 2){
console.log(clickedElement);//Last clickedclicked
}
}

How do I pass (or reference) "$(this)" from html event?

Let's say I have a button in a table which adds a new row to a table:
<td><a onclick="addRow()"></a></td></tr>...
and I want to reference $(this) or $(this).closest('tr') from the function at the bottom of the page.
function addRow(){
$(this) // contains all information from the row which pressed the button
}
Simply passing a javascript variable from the HTML will result in null (as expected). Is there a way to reference the row that pressed the button?
The RECOMMENDED way of doing this is unobtrusive and delegated - give the link a class:
var $tb = $("#someTable");
$tb.on("click", ".addRow", function(e) { // delegation to allow new rows' links to work
e.preventDefault(); // stop any click side effects
var $row = $(this).closest("tr");
$tb.append($row.clone())
});
a { text-decoration:none }
td,th { padding:3px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>Add</th>
</tr>
</thead>
<tbody id="someTable">
<tr>
<td>1st</td>
<td>2nd</td>
<td><a class="addRow" href="#">+</a></td>
</tr>
<tr>
<td>3rd</td>
<td>4th</td>
<td><a class="addRow" href="#">+</a></td>
</tr>
</tbody>
</table>
Use this
<td><a onclick="addRow(this)"></a></td></tr>
and then:
function addRow(e){
console.log($(e)) // contains all information from the row which pressed the button
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a onclick="addRow(this)">Clickme</a>
You can reference the row that you clicked using an event.
<td>Add</td>
and in javascript you can check the event
<script>
function addRow(event) {
console.log(event);
}
</script>

How to handle a TR click without the first and last TD

I have a Datatables Table with some random values in it. I would like to create a popup when the client clicks on the TR itself, but NOT on the first and the last TD of the table.
<table class="table href="#popup">
<tr id="tr1">
<td><input type="checkbox"></td>
<td>Test1</td>
<td>Test1</td>
<td><input type="checkbox"></td>
</tr>
<tr id="tr2">
<td><input type="checkbox"></td>
<td>Test1</td>
<td>Test1</td>
<td><input type="checkbox"></td>
</tr>
<tr id="tr3">
<td><input type="checkbox"></td>
<td>Test1</td>
<td>Test1</td>
<td><input type="checkbox"></td>
</tr>
<tr id="tr4">
<td><input type="checkbox"></td>
<td>Test1</td>
<td>Test1</td>
<td><input type="checkbox"></td>
</tr>
</table>
My popup plugin works like, if an href link is called and the popup div's id equals to that href value, it automatically pops up.
However if someone clicks on the first or the last TD do NOT want the popup to activate. Is it actually possible to achieve this somehow?
(The following solution should not be mentioned, because it would make the code look like a mess literally: if I select all the TD fields without the first and last, and add a href attribute to all of the selected TD elements.)
Any other suggestions are welcomed!
When you click, the event is propagated from the child nodes to the parent nodes (learn more here).
You can disable event propagation in both td:first-child and td:last-child elements inside your table in order to prevent your tr event handler from being reached.
I'd also suggest you to use event delegation to keep better performance.
$('.table').on('click', 'tr', function() {
alert('show popup');
});
$('.table').on('click', 'td:first-child, td:last-child', function(e) {
e.stopPropagation();
});
FIDDLE: http://jsfiddle.net/6QTrL/1/
Just use this:
Using :first-child and :last-child with not()
$('table tbody tr td').not(":first-child").not(":last-child").click(function(
//This will only be triggered on the td that are not the first or the last on a tr
))
Here's a fiddle to accomplish that - First and Last row now clickable
I have the first and last row throwing an alert but that's just to give you an idea of how to target them.
$(function(){
var tableRows = $('table').find('tr');
$('table').on('click', 'tr', function(){
if (this == tableRows[0])
alert('first row');
else if (this == tableRows[tableRows.length - 1])
alert('last row');
else
alert('somewhere in the middle');
});
});
The code below is probably more along the lines of what you're looking for. I made the code above in the fiddle so I just pasted that as well.
$(function(){
var tableRows = $('table').find('tr');
$('table').on('click', 'tr', function(){
if (this != tableRows[0] && this == tableRows[tableRows.length - 1])
alert('somewhere in the middle');
});
});

How to create one javascript/jquery function-handler for many items?

I have the html like below:
<table class="table" id="subscriptions">
<tbody id="subscriptions-tbody">
<tr>
<td>Item 1</td>
<td>delete</td>
</tr>
<tr>
<td>Item 2</td>
<td>delete</td>
</tr>
<tr>
<td>Item 3</td>
<td>delete</td>
</tr>
</tbody>
</table>
Items can be added dynamically there.
Now, I should create the function, which will help me to delete the element from the list, if user clicks delete.
Looks like I should:
assign some unique id for each item in the list (I have such ids) - where should I keep them? part as href?;
once user clicks on the link, I should prevent default action and pass control to my function (it will hide the element from the list and will sent POST request to the server) with item id as parameter.
How to do it?
This is the perfect case for event delegation. Hook the event on the table or tbody, but ask jQuery to trigger it only if it happens on your delete link, like this:
$("#subscriptions-tbody").delegate("a", "click", function(event) {
var row = $(this).closest('tr');
// ...delete the row
return false; // Don't try to follow the link
});
Live Example | Source
Because the event is hooked on the table or tbody, adding and removing rows doesn't matter, because the event is handled at the table or tbody level.
In the above, I'm using delegate because I like how explicit is is. With jQuery 1.7 or higher, you can use the way-too-overloaded-on function instead:
$("#subscriptions-tbody").on("click", "a", function(event) {
var row = $(this).closest('tr');
// ...delete the row
return false; // Don't try to follow the link
});
Live Example | Source
Note that the order of arguments is slightly different.
You should keep the information required for the server side (like the id) on the tr with data- attributes, and use .on() to handle the events from the table..
html
<table class="table" id="subscriptions">
<tbody id="subscriptions-tbody">
<tr data-id="3">
<td>Item 1</td>
<td>delete</td>
</tr>
<tr data-id="5">
<td>Item 2</td>
<td>delete</td>
</tr>
<tr data-id="6">
<td>Item 3</td>
<td>delete</td>
</tr>
</tbody>
</table>
script
$("#subscriptions").on("click", "a.delete", function(e) {
e.preventDefault();
var row = $(this).closest('tr'),
relatedId = row.data('id');
$.post(...); // use relatedId here
row.fadeOut(500, function(){
row.remove();
})
});
Try this:
<table class="table" id="subscriptions">
<tbody id="subscriptions-tbody">
<tr data-id="1">
<td>Item 1</td>
<td>delete</td>
</tr>
<tr data-id="2">
<td>Item 2</td>
<td>delete</td>
</tr>
<tr data-id="3">
<td>Item 3</td>
<td>delete</td>
</tr>
</tbody>
</table>
You will name a class for your delete anchors, let's say class="delete", and you will place data-id attribute to the table row in order to unique identify each item and know what id to send to the server.
Now your js might look like this:
$("#subscriptions-tbody").on('click', 'a.delete', function(e){
var tr = $(e.currentTarget).closest('tr');
//get the id
var id = tr.attr("data-id");
//make ajax request
$.ajax({
url: 'script.php',
data: id,
success: function(data) {
//hide the item or remove
tr.remove(); // tr.hide();
// ajax callback
}
});
});
You can store the ID as a data- attribute on either the control or the row. Delegate the click handler to the table itleslf to account for dynamically added elements that don't exist when code is run using on() method.
HTML:
<!-- class added to element -->
delete
JS
$('#subscriptions').on('click', '.delete-btn',function(evt){
evt.preventDefault();
var id=$(this).data('id'), $row=$(this).closest('tr');
/* send data to server and remove row on success*/
$.post('serverUrl.php', { rowID: id, action :'delete'}, function(){
$row.remove();
})
})

delete table row

I have a table like this:
<table>
<tr>
<td>foo</td>
<td><button>delete</delete></td>
</tr>
<tr>
<td>foo</td>
<td><button>delete</delete></td>
</tr>
</table>
I want to use JQuery to install a click handler on the delete buttons such that it deletes the current row when clicked
Give a class of, for example, "delete" to the delete buttons, then use this:
$("button.delete").click(function() {
$(this).closest("tr").remove();
});
Alternatively, if you can't add the class, you can use the :contains selector:
$("button:contains('delete')").click(function() {
$(this).closest("tr").remove();
});
Update (now that the code in the question has completely changed)
Now that you have changed the code in the question to contain only one button instead of two, you don't need to bother adding the class, or using the :contains selector, you can just use the plain old button selector:
$("button").click(function() {
$(this).closest("tr").remove();
});
Try this. As a side not you should not have same id to any dom element on the page.
$("button").click(function() {
$(this).closest("tr").remove();
});
In your markup the tags are not closed properly. E.g the button tag is not closed properly so the selector will not work. Give a unique id or a class name to select the required buttons.
Something like this
<tr>
<td>foo</td>
<td>Some content</td>
<td><input type="button" class="delete" value="Delete" /></td>
</tr>
Using delegate to attach event handler only to table for better performance. This way the click event will be attached only to the table element no matter how many rows it has.
$("table").delegate("input.delete", "click", function() {
$(this).closest("tr").remove();
});
You can try soemthing like this:
<table>
<tr>
<td>row 1, cell 1</td>
<td><img class="delete" src="del.gif" /></td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td><img class="delete" src="del.gif" /></td>
</tr>
</table>
And your jQuery:
$('table td img.delete').click(function(){
$(this).parent().parent().remove();
});
First off, there's a syntax error in your HTML, and you should a class identifier for easier access to those buttons:
<table>
<tr>
<td>foo</td>
<td><button class="delete">delete</button></td>
</tr>
<tr>
<td>foo</td>
<td><button class="delete">delete</button></td>
</tr>
</table>
Next, here's the jQuery code you need:
$(function() {
$('button.delete').click(function(event) {
event.preventDefault();
$(this).closest('tr').remove();
});
});

Categories