How to specify an onclick parameter in jQuery? - javascript

I'm having a tough time using jQuery to give a button the ability to delete it's own row. Specifically, I the selection process find extremely confusing.
The table has an id of foo and the button has a class of 'delete. Shouldn't the following code select the button? It's just the ****.on('click', function(event){}) part that I am struggling to understand. I just want the button created to be selected to have the on response.
$('#foo tr:last').after(`<tr id="1"><td>fname</td>
<td>lname</td>
<td>pnumber</td>
<td>address</td>
<td><button class="delete" id="1" type="click">Delete</button></td>`)
$("#foo .delete").on('click', function(event) {
event.preventDefault()
let rowID = event.target.id
if (rowID !== '') {
$(`#foo,#${rowID}`)[1].remove()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="foo">
<tr></tr>
</table>

Read this Jquery doc https://learn.jquery.com/events/event-delegation/
$(document).on('click', "#foo .delete", function(event){
//do something here
})

Related

Disable click fot td for particular column using Jquery

I have tried to use Jquery to click a table row to go to a new page. But my last column has a button. For which clicking on the edge takes it to a new page. Anyway to disable the td onclick for that column. I tried using onclick='event.stopPropagation();return false;' but that would disable the button too.
My Jquery code below.
$(".myTable").on("click", "td", function(){
var issueid = $(this).closest('tr').find("td:eq(2) input").val();
window.location = 'viewminissues.jsp?issue_id='+issueid;
});
This can be handled in two ways:
Try adding event.preventDefault() along with event.stopPropagation().
Add a disabled class on the td element manually and then handle further scenarios with hasClass('disabled') check.
The issue is because the click event from the button propagates up the DOM to the tr which then transfers the page.
To fix this you could call stopPropagation() within the button event handler:
$(".myTable").on("click", "td", function() {
var issueid = $(this).closest('tr').data('issue');
console.log('Transferring to: viewminissues.jsp?issue_id=' + issueid);
//window.location.assign('viewminissues.jsp?issue_id=' + issueid);
});
$('.myTable').on('click', 'button', function(e) {
e.stopPropagation();
console.log('Perform button action...');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="myTable">
<tr data-issue="1">
<td>Foo bar</td>
<td><button>Edit</button></td>
</tr>
<tr data-issue="2">
<td>Lorem ipsum</td>
<td><button>Edit</button></td>
</tr>
</table>
You can exclude the last <td> from the click() event using :not(:last) like this:
$(".myTable").on("click", "td:not(:last)", function() {
var issueid = $(this).closest('tr').find("td:eq(2) input").val();
window.location = 'viewminissues.jsp?issue_id=' + issueid;
});

how to add onclick events to dynamically generated buttons and show /hide the table

I have many buttons generating dynamically based on end user request
$out='<input class="show_hide" type="button" id="'.$platform_name.'" value="'.$platform_name.'"/>';
the same variable name tables also coming dynamically
$out.='<table id="'.$platform_name.'" > </table>
if suppose button
<input class="show_hide" type="button" id="button1'" value="button1"/>
<table id="button1" > </table>
how to get the number of button names/id, and based on button name/id finding table and show/ hide the table. Please help me. i am fresher in php
when it comes to dynamic binding, go for delegates
$( "body" ).on( "click", ".show_hide", function() {
$( this ).next().toggle();
});
OR you can provide selector in sibling selection
$( "body" ).on( "click", ".show_hide", function() {
$( this ).next("#table1").toggle();
});
this code will hide/show the next sibling(in your case a table) on button click with class show_hide
The id should be unique in your HTML. E.g.
<input class="show_hide" type="button" id="button1'" value="button1"/>
<table id="table1"></table>
Then, you can 'choose' either the button or the table with jQuery using:
$('#button1')
$('#table1')
E.g.
for (var i = 1; i <= numberOfTables; i++) {
$('#button' + i).click(function() {
$('#table' + i).hide();
});
}
If you want to add event handler dynamically to element, ensure that you can have id for that element, you can do using plain javascript,
elemm.onclick = function() { alert('blah'); };
where elemm = document.getElementById("button1")
try like this using delegate:
all button click event:
$(document).on( ".show_hide", "click", function() {
//all button click
})
for the table use wildcart:
$(document).on( "[id^=table]", "click", function() {
//all table click
})
you also use wildcart for button also like this:
$(document).on( "[id^=button]", "click", function() {
//all table click
})
As others have said, id's must be unique. Your button and table can't have the same id. But you can use the value of your button to find the associated table:
$out='<input class="show_hide" type="button" value="'.$platform_name.'"/>';
Since the buttons are dynamic, you don't know the ids of all of the buttons, but you can use the jQuery class selector to find all buttons with the show_hide class and apply a function to the click event:
$("input.show_hide").on('click', function () {
// get the id of the table associated with the button
var tableId = $(this).val(),
// toggle your table between hide and shown
$("#" + tableId).toggle();
});
If your tables can be added dynamically AFTER the page loads, you will have to use a delegate for defining the click event:
$(document).on( ".show_hide", "click", function() {
.. same code goes here
});

On Click event on <td> created dynamically

I have the following table which is created dynamically using a onload function at the beginning.
<div id="first">
<table class="joma" id="joma">
<tbody>
<tr>
<th>Id</th>
<th>V No</th>
<th>Biboron</th>
<th>Taka</th>
</tr>
<tr><td class="rid">1</td><td>sss</td><td>222</td><td class="cv">4</td></tr>
<tr><td class="rid">2</td><td>xxx</td><td>2333</td><td class="cv">4</td></tr>
</tbody>
</table>
</div>
Now I need to be able to click the <td class="rid"> which should give the the corresponding value. in this case 1 or 2.
How do I do this?
I have used the following methods:
$(document).ready(function() {
$('.rid').click(function() {
alert(this);
});
});
$('.rid').click(function() {
alert(this);
});
I am not getting anything with this.
Use .on()
$(document).on('click','.rid',function() {
alert("this");
});
when page loaded DOM is created .rid is not the part of the page.
So you can not access them directly you have to use event delegation
Use event delegation:
$(document).on('click', '.rid', function() {
alert("this");
});
.rid doesn't exist on page load, so bind it to an element that does exist (usually the container to where your appending the content, but since I didn't see one, document is a safe bet).
$(document).ready(function() {
$('.rid').click(function() {
alert($(this).html());
});
});
the fiddle : http://jsfiddle.net/yraQS/

Javascript and jquery stop event

I have a small issue:
I have a jquery onclick event set for a row() in a table and in the last column I have a link that opens a confirmation pop-up(asking if I am sure to do that bla bla . . .). If I click the link, the pop-up opens, and if I press no, it should stay on the current page, but instead it continues with the event from the row(that click is triggered). What do you think?
Link:
<tr class="clickableRow" id="someId"> bgcolor="color">
..........
<td>
<img src="images/delete.png" border="0">
</td>
</tr>
Javascript:
$(".clickableRow").click(function() {
window.open("companynewestimate.php?id="+this.id,"_parent");
});
Del function
<script language="javascript">
function del_prompt(id)
{
if(confirm ("Are you sure you want to delete selected Record")){
location.href = "companyopenestimates.php?act=del&id="+id;
}
else{
return false;
}
}
</script>
Without some code, it's hard to get the correct answer. But maybe this helps:
$("#element").on("click",function(e){
//do something
e.preventDefault();
e.stopPropagation();
})
See here:
http://api.jquery.com/event.stopPropagation/
Changing your link's onclick should do the trick:
onClick="del_prompt('<?=$line['id_est']?>'); return false;"
Note that the javascript: is not at all needed.

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>

Categories