Bind event on element that's not in dom - javascript

I have a script that adds a <tr> dynamically, outside it seems that the elements contained in it are not recognized by jQuery because it is not yet loaded into the DOM.
I try to use .on function , but it is not working.
Have you an idea ?
$(document).ready(function(){
$("#add_item").click(function(e){
e.preventDefault();
var nbeTr = $(".tablerow").length;
if (nbeTr < 10){
$(".tablerow:last").after("<tr class='filleul'><td></td><td></td><td></td><td><button class='newtr'>X</button></td></tr>");
}
});
$(document).on("click", ".newtr", function(event) {
event.preventDefault();
alert("Yo");
});
});

You'll need to register the event listener when creating the button element. Right now you're trying to register click events to undefined elements.
// create button
$ele = $("<button class='newtr'>X</button>");
// bind event listener to button
$ele.on("click", function() { alert("hello"); });
// insert $ele into DOM
$target.append($ele);

Hey Buck your code is working, I think problem is some where else.
See this working example:
$(document).ready(function() {
$("#add_item").click(function(e) {
e.preventDefault();
var nbeTr = $(".tablerow").length;
if (nbeTr < 10) {
$(".tablerow:last").after("<tr class='tablerow filleul'><td>1</td><td>2</td><td>3</td><td><button class='newtr'>X</button></td></tr>");
}
});
$(document).on("click", ".newtr", function(event) {
event.preventDefault();
alert("Yo");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id='add_item'>Add item</button>
<table>
<tr class='tablerow'>
<td>c1</td>
<td>c2</td>
<td>c3</td>
<td>
<button class='newtr'>X</button>
</td>
</tr>
<table>

Ok, the problem was a bad version of jQuery was using.
I just use CDN of last jQuery version and refresh cache and it's working.

Related

trigger click event in table

This is my jquery code:
$("#tableGrid").on("click", "tr", function (event) {
var link = $(this).find('.view-icon');
link.trigger('click');
console.log(link);
});
and I want to trigger this
<table id="tableGrid">
<tr>
<td>
<div class='line-item-icons'>
<i class='icon-view view-icon' data-url="${filePath}"></i>
</div>
</td>
</tr>
</table>
but I receive this error:
Failed to start loading
How to solve this problem? The icon is inside the table.
Try this out in your jquery.Hope this works
$("#tableGrid").on("click", "tr", function (event) {
var link = $(this).find('.view-icon');
link.trigger('click',link);
});
$('.view-icon').click(function(e,link){
e.stopPropagation();
console.log(link);
});
Here only difference is that the link that you get in console.log(link) is element and not a jquery object. if you want it as a jquery object just wrap it as console.log($(link))
Update your jQuery in this way -
$("#tableGrid tr").on("click", function (event) {
var link = $(this).children('.view-icon');
link.trigger('click');
console.log(link);
});

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;}

JQuery: Disable click event

I want to disable all click events on my page but some of events are still getting called, suppose I have html as below
<div id='parent'>
<table>
<tr>
<td><input type = 'text'/></td>
<td><select><option>A</option><option>B</option></select></td>
<td>Click </td>
</tr>
<tr>
<td>dscsdcd</td>
<td>dscsdcd</td>
<td>dscdscdsc</td>
</tr>
<tr>
<td>sdcdsc</td>
<td>dssdcdsc</td>
<td><input type='submit' value='Button'/></td>
</tr>
</table>
</div>
And script as below
$('#parent').click( function(e)
{
e.stopPropagation();
e.preventDefault();
e.stopImmediatePropagation();
return false;
});
when I click anchor tag, it alerts Called which it shouldn't because I am disabling event for it's parent. Looks like anchor tag is overriding onclick, if it is then how to prevent it? if not, then what could be the solution?
JS Fiddle
Just remove the onclick attribute from elements that have it, and unbind the 'click' event using .off('click') method
$('#parent *[onclick]').removeAttr('onclick').off('click');
onclick attribute has a higher priority here. You can loop your <a> elements and unset this attribute:
$('#parent a').each(function () {
$(this).attr('onclick', '');
}).click(function () {
// ...
});
try this plugin to temporary disable onclick AND jQuery click events:-
$.fn.disableClick = function (disable){
this.each(function() {
if(disable){
if(this.onclick)
$(this).data('onclick', this.onclick).removeAttr('onclick');
if($._data(this, 'events') && $._data(this, 'events').click)
$(this).data('click', $.extend(true, {}, $._data(this, 'events').click)).off('click');
}
else{
if($(this).data('onclick'))
this.onclick = $(this).data('onclick');
if($(this).data('click'))
for(var i in $(this).data('click'))
$(this).on('click', $(this).data('click')[i].handler);
}
});
return this;
};
//disable clicks
$('#parent *').disableClick(true);
//enable clicks
$('#parent *').disableClick(false);
DEMO
There is an attribute you should use to make all things disabled.
var nodes = document.getElementById("parent").getElementsByTagName('*');
for(var i = 0; i < nodes.length; i++) {
nodes[i].disabled = true;
}
Unfortunately disable is not valid with anchor tags.
There you should use :
var nodes = document.getElementById("parent").getElementsByTagName('a');
for(var i = 0; i < nodes.length; i++) {
nodes[i].onclick = function(e){
e.preventDefault();
// YOUR CODES HERE
}
}
try to combine these two methods according to your needs
If you want to disable it for any element under that div you must type:
$('#parent *').click( function(e)
{
e.stopPropagation();
e.preventDefault();
e.stopImmediatePropagation();
return false;
});

Why aren't these buttons deleting the rows that contain them?

What I'm trying to do with the following snippet should be self-explanatory
<tbody id="slide-table-body">
</tbody>
</table>
<button class="wp-core-ui button-primary" type="button" onclick="addAnotherSlide()">Add another carousel item</button>
<script type="text/javascript">
var newRowHtml = '<tr><td>(assetprevurl)</td><td>(asseturl)</td><td><button type="button" class="wp-core-ui button-primary deleteSlideButton">Delete Slide</button></td></tr>';
function addAnotherSlide() { jQuery('#slide-table-body').append(newRowHtml); }
jQuery(function($){
$('.deleteSlideButton').click(function() { $(this).closest('tr').remove();});
</script>
My problem is that
$('.deleteSlideButton').click(function() { $(this).closest('tr').remove();} );
isn't deleting the row and I can't figure out why.
This is because you're adding the html after the DOM is loaded, try using Jquery on :
$( ".deleteSlideButton" ).on( "click", function() {
console.log($(this));
});
It's cause you've attached an event handler to a newly created DOM element. Change it to:
$('.deleteSlideButton').on("click", function() {
// do something
});
This may also help: Difference between .on('click') vs .click()

Jquery append input element and send data from that input element

I have this simple HTML code:
<div id="new_gallery">
<p id="add_gallery">Add new gallery</p>
</div>
and jQuery code:
<script>
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" />Add');
$(this).remove();
});
$("#create_new_gallery").on('click', function(){
alert('1');
});
</script>
First function is working, but second one is not. I need to create new input element, send data via ajax, and then delete the input element and append a p element once again. How can I do this?
When the second statement runs, the element #create_new_gallery does not exist yet so it does nothing.
You can do the binding to the click event after you created the element for instance, this ensures the element exists in the DOM:
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name="new_gallery" />Add');
$(this).remove();
$("#create_new_gallery").on('click', function() {
alert('1');
});
});​
DEMO
Here is a little bit more optimized version. It's a bit non-sense to append an element and have to re-query for it (event though querying by id is the fastest method. Besides, it's best to use the chaining capabilities of jQuery afterall:
$("#add_gallery").click(function() {
var $gallery = $("#new_gallery");
$('<input name="new_gallery" />').appendTo($gallery);
$('Add')
.on('click', function() {
alert('1');
})
.appendTo($gallery);
$(this).remove();
});​
DEMO
#create_new_gallery doesn't exist when you bind its click event.
Here is what your code should look like:
$("#add_gallery").click(function() {
var newG = $("#new_gallery");
$('<input name"new_gallery" />').appendTo(newG);
$('Add').appendTo(newG).on('click',
function() {
alert('1');
});
$(this).remove();
});
Notice that getting $("#new_gallery") into a variable avoid to look for it twice.
$(document).ready(function () {
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" />Add');
$(this).remove();
$("#create_new_gallery").on('click', function(){
alert('1');
});
});
});
DEMO: http://jsfiddle.net/39E4s/2/
​
Try live to handle the events fired for elements added after the page has loaded.
$("#create_new_gallery").live('click', function(){
alert('1');
});
http://api.jquery.com/live/

Categories

Resources