Reload Jquery .on event handler - javascript

I have a table with inputs. The user can start type and a JQuery script (https://jqueryui.com/autocomplete/#multiple) autocompletes users text.
The user can also add new inputs to the table with a simple JavaScript createElement and innerHTML function.
The problem arrives when the user adds the new inputs because JQuery doesn't register the new inputs and therefore it doesn't attach an event handler to autocomplete users text.
One solution that may work (but I couldn't get it to work) is the JQuery .delegate() function.
EDIT (Added source code):
https://jsfiddle.net/j8rz7s1q/7/
Can't get the code to format correctly from jsfiddle

From http://api.jquery.com/on/
Delegated event handlers have the advantage that they can process
events from descendant elements that are added to the document at a
later time.By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
Then, you just need to change the following example to match the elements that you have:
$( "#dataTable tbody" ).on( "click", "tr", function() {
console.log( $( this ).text() );
});

you need to use a delegate event to handle newly added elements
something like:
$(document).on("keydown", "tr input", function() {})

Ordinarily, binding an event on elements that do not exist yet is handled through delegation, where you bind on a parent element and rely on the event on any children created after the binding to work by bubbling up to the parent, which then can invoke the callback.
In the case of the jQuery UI Autocomplete plugin, it's implemented by applying the autocomplete to an element through its implemented interface, which does its own binding on the elements it's being used on.
In this case, where new DOM elements are being added, we define a function that handles binding the Autocomplete functionality on whatever elements are passed to it, and update the code that creates the new elements to call that function after creation to apply the Autocomplete bindings.
A working demonstration of this is in https://jsfiddle.net/j8rz7s1q/16 and duplicated here:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<button onClick="addInputs();" id="button1">Add input</button>
<p>
The first input works. The autocomplete works completely but when you add new inputs the new inputs doesn't register to the event handler.
</p>
<div>
<div class="LightBox-box-content">
<table>
<tbody class="addInput">
<tr>
<td>
<input type="text" class="input1">
</td>
</tr>
</tbody>
</table>
</div>
</div>
<script>
$(function() {
var availableTags = [
"Yes", "No",
];
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
window.setupAutocomplete = function($obj) {
return $obj
// don't navigate away from the field on tab when selecting an item
.on("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).autocomplete("instance").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join("");
return false;
}
});
};
setupAutocomplete($(".input1"));
});
</script>
<script>
function addInputs() {
var div = document.createElement('tr');
div.innerHTML = '<tr>\
<td>\
<input type="text" class="input1">\
</td>\
</tr>';
setupAutocomplete($('input', div));
document.getElementsByClassName('addInput')[0].appendChild(div);
}
</script>
</body>
</html>

Related

How to handle events on dynamically added elements in jQuery

A fairly straightforward question - Why doesn't mouseover trigger for (text) inputs which are dynamically generated after the page has loaded?
I can get it to work for checkbox, select, textarea...
Below code doesn't give an event
$(document).ready(function () {
$(`input[type=text]`).on(`mouseover`, function (e) {
console.log(e);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text">
Below code gives an event for everything but text input:
$(document).ready(function () {
$(`input, textarea, [type=checkbox], select`).on(`mouseover`, function (e) {
console.log(e);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input>
<textarea></textarea>
<input type="checkbox">
<select>
<option>test</option>
</select>
How can I trigger mouseover event for a text input?
EDIT: The text inputs are dynamically generated after the document has loaded.
Thank you
You need to pass a second parameter to .on that allows for event delegation:
$(document).ready(function () {
// Set the handler up on something you know will be there from the start
// that the event(s) that get triggered later can "bubble" up to. That's
// document in this case.
// The second argument becomes what you want the event to be handled on
$(document).on(`mouseover`, "input[type='text']", function (e) {
console.log(e);
});
// Create a new element after the handler has been set up
$(document.body).append('<input type="text">');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Call a function outside AJAX when I click button inside the ajax response [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I want to bind an onclick event to an element I insert dynamically with jQuery
But It never runs the binded function. I'd be happy if you can point out why this example is not working and how I can get it to run properly:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da">
<head>
<title>test of click binding</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
jQuery(function(){
close_link = $('<a class="" href="#">Click here to see an alert</a>');
close_link.bind("click", function(){
alert('hello from binded function call');
//do stuff here...
});
$('.add_to_this').append(close_link);
});
</script>
</head>
<body>
<h1 >Test of click binding</h1>
<p>problem: to bind a click event to an element I append via JQuery.</p>
<div class="add_to_this">
<p>The link is created, then added here below:</p>
</div>
<div class="add_to_this">
<p>Another is added here below:</p>
</div>
</body>
</html>
EDIT: I edited the example to contain two elements the method is inserted to. In that case, the alert() call is never executed. (thanks to #Daff for pointing that out in a comment)
All of these methods are deprecated. You should use the on method to solve your problem.
If you want to target a dynamically added element you'll have to use
$(document).on('click', selector-to-your-element , function() {
//code here ....
});
this replace the deprecated .live() method.
The first problem is that when you call append on a jQuery set with more than one element, a clone of the element to append is created for each and thus the attached event observer is lost.
An alternative way to do it would be to create the link for each element:
function handler() { alert('hello'); }
$('.add_to_this').append(function() {
return $('<a>Click here</a>').click(handler);
})
Another potential problem might be that the event observer is attached before the element has been added to the DOM. I'm not sure if this has anything to say, but I think the behavior might be considered undetermined.
A more solid approach would probably be:
function handler() { alert('hello'); }
$('.add_to_this').each(function() {
var link = $('<a>Click here</a>');
$(this).append(link);
link.click(handler);
});
How about the Live method?
$('.add_to_this a').live('click', function() {
alert('hello from binded function call');
});
Still, what you did about looks like it should work. There's another post that looks pretty similar.
A little late to the party but I thought I would try to clear up some common misconceptions in jQuery event handlers. As of jQuery 1.7, .on() should be used instead of the deprecated .live(), to delegate event handlers to elements that are dynamically created at any point after the event handler is assigned.
That said, it is not a simple of switching live for on because the syntax is slightly different:
New method (example 1):
$(document).on('click', '#someting', function(){
});
Deprecated method (example 2):
$('#something').live(function(){
});
As shown above, there is a difference. The twist is .on() can actually be called similar to .live(), by passing the selector to the jQuery function itself:
Example 3:
$('#something').on('click', function(){
});
However, without using $(document) as in example 1, example 3 will not work for dynamically created elements. The example 3 is absolutely fine if you don't need the dynamic delegation.
Should $(document).on() be used for everything?
It will work but if you don't need the dynamic delegation, it would be more appropriate to use example 3 because example 1 requires slightly more work from the browser. There won't be any real impact on performance but it makes sense to use the most appropriate method for your use.
Should .on() be used instead of .click() if no dynamic delegation is needed?
Not necessarily. The following is just a shortcut for example 3:
$('#something').click(function(){
});
The above is perfectly valid and so it's really a matter of personal preference as to which method is used when no dynamic delegation is required.
References:
jQuery docs for .on()
jQuery docs for .click()
jQuery docs for .live()
Consider this:
jQuery(function(){
var close_link = $('<a class="" href="#">Click here to see an alert</a>');
$('.add_to_this').append(close_link);
$('.add_to_this').children().each(function()
{
$(this).click(function() {
alert('hello from binded function call');
//do stuff here...
});
});
});
It will work because you attach it to every specific element. This is why you need - after adding your link to the DOM - to find a way to explicitly select your added element as a JQuery element in the DOM and bind the click event to it.
The best way will probably be - as suggested - to bind it to a specific class via the live method.
It is possible and sometimes necessary to create the click event along with the element. This is for example when selector based binding is not an option. The key part is to avoid the problem that Tobias was talking about by using .replaceWith() on a single element. Note that this is just a proof of concept.
<script>
// This simulates the object to handle
var staticObj = [
{ ID: '1', Name: 'Foo' },
{ ID: '2', Name: 'Foo' },
{ ID: '3', Name: 'Foo' }
];
staticObj[1].children = [
{ ID: 'a', Name: 'Bar' },
{ ID: 'b', Name: 'Bar' },
{ ID: 'c', Name: 'Bar' }
];
staticObj[1].children[1].children = [
{ ID: 'x', Name: 'Baz' },
{ ID: 'y', Name: 'Baz' }
];
// This is the object-to-html-element function handler with recursion
var handleItem = function( item ) {
var ul, li = $("<li>" + item.ID + " " + item.Name + "</li>");
if(typeof item.children !== 'undefined') {
ul = $("<ul />");
for (var i = 0; i < item.children.length; i++) {
ul.append(handleItem(item.children[i]));
}
li.append(ul);
}
// This click handler actually does work
li.click(function(e) {
alert(item.Name);
e.stopPropagation();
});
return li;
};
// Wait for the dom instead of an ajax call or whatever
$(function() {
var ul = $("<ul />");
for (var i = 0; i < staticObj.length; i++) {
ul.append(handleItem(staticObj[i]));
}
// Here; this works.
$('#something').replaceWith(ul);
});
</script>
<div id="something">Magical ponies ♥</div>
function load_tpl(selected=""){
$("#load_tpl").empty();
for(x in ds_tpl){
$("#load_tpl").append('<li><a id="'+ds_tpl[x]+'" href="#" >'+ds_tpl[x]+'</a></li>');
}
$.each($("#load_tpl a"),function(){
$(this).on("click",function(e){
alert(e.target.id);
});
});
}
I believe the good way it to do:
$('#id').append('<a id="#subid" href="#">...</a>');
$('#subid').click( close_link );
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click', '.close', function(){
var rowid='row'+this.id;
var sl = '#tblData tr[id='+rowid+']';
console.log(sl);
$(sl).remove();
});
$("#addrow").click(function(){
var row='';
for(var i=0;i<10;i++){
row=i;
row='<tr id=row'+i+'>'
+ '<td>'+i+'</td>'
+ '<td>ID'+i+'</td>'
+ '<td>NAME'+i+'</td>'
+ '<td><input class=close type=button id='+i+' value=X></td>'
+'</tr>';
console.log(row);
$('#tblData tr:last').after(row);
}
});
});
</script>
</head>
<body>
<br/><input type="button" id="addrow" value="Create Table"/>
<table id="tblData" border="1" width="40%">
<thead>
<tr>
<th>Sr</th>
<th>ID</th>
<th>Name</th>
<th>Delete</th>
</tr>
</thead>
</table>
</body>
</html>

add event for sub children in jquery

Just a little help for me here with jquery.
This is my problem. I have a list
<ul>
<li>
<p>Name</p>
Delete
</li>
</ul>
the 'Delete' event click was initiation in jquery when load page. So the issue now, i'd like to add an element <li></li> which contain children like above. I used jquery to create the tag 'li' contain children, then 'prepend' to the 'ul'.
The problem is, i can not call 'delete' event on new item. Somebody help me please
try this DEMO
var contentToAdd = ' <li> <p>Name</p> Delete </li>';
$('ul').prepend(contentToAdd);
$('ul').on('click','a', function(){
alert('click');
});
The problem is that you're most probably using .click or bind('click') to attach the click event handler to the element. This is fine if all of the elements exist at the time when you attach the event, if however you create new elements that match that same selector, they will not get that event attached.
You need to use the delegate() or .on() method to attach the event to all elements that are current on the page or are appended to the page after they're set up.
An example of a delegate that catches the click event and appends a new element that you can click and see that the same event is attached to each new part of the DOM that matches the selector.
$('#list').delegate('a','click',function() {
alert('Click event fired - Adding a new element to test!');
$('ul').append('<li><p>Name</p>Delete</li>');
return false;
});
Or using the newer .on method:
$('#list').on('click','a',function() {
alert('Click event fired - Adding a new element to test!');
$('ul').append('<li><p>Name</p>Delete</li>');
return false;
});
$('#list') is what my example uses to denote the <ul>, but you could just as easily use $('ul') if you don't want to put an id or class on the list.
Example Fiddle
take a look at this jQuery example:
(one of the last examples on http://api.jquery.com/on/)
<!DOCTYPE html>
<html>
<head>
<style>
p { background:yellow; font-weight:bold; cursor:pointer;
padding:5px; }
p.over { background: #ccc; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<p>Click me!</p>
<span></span>
<script>
var count = 0;
$("body").on("click", "p", function(){
$(this).after("<p>Another paragraph! "+(++count)+"</p>");
});
</script>
</body>
</html>
which means in your case you need something like:
$("ul").on("click", "a", function(e){
// delete logic goes here
})
Add the click listener on the UL rather than the a's themselves. This way it will automatically detect clicks to newly added items as well.
$(document).ready(function() {
$("ul").on("click li > a", function() {
$(this).closest("li").remove();
});
});
You can use the .on() method to do so,
The .on() method attaches event handlers to the currently selected set
of elements in the jQuery object
$(document).on("click", "ul li a"), function(){
//your code here
});
Test Link
You can try this,
$("ul").on("click", "a", function(e){
e.preventDefault();
$(this).closest('li').remove();
});
Okay, given that ".on" doesn't meet your requirements, perhaps something like:
$element = $('<li><p>Name</p>Delete</li>');
$element.find("a").click(function(){
//call your delete function
})
$("ul").prepend($element);
Why dont you use jquery templating.
You can define a text/template and iterate over it to get your desired result.
an example:
**THIS IS YOUR SCRIPT**
<script id="movieTemplate" type="text/x-jquery-tmpl">
<li><b>${Name}</b> was released in ${ReleaseYear}.</li>
</script>
**THIS IS THE JQUERY TEMPLATE**
<script type="text/javascript">
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999" },
{ Name: "The Inheritance", ReleaseYear: "1976" }
];
// Render the template with the movies data and insert
// the rendered HTML under the "movieList" element
$( "#movieTemplate" ).tmpl( movies )
.appendTo( "#movieList" );
</script>
**THIS IS YOUR HTML**
<ul id="movieList"></ul>
More examples :
http://blog.reybango.com/2010/07/09/not-using-jquery-javascript-templates-youre-really-missing-out/

How can I temporarily disable click events on a button without actually disabling it?

Using jQuery, I would like to, without changing the disabled attribute of a given button, disable all click events for it.
I was thinking of retrieving the click event handlers, unbind them, and storing them (say, using data()).
Then I can re-bind them once the button is enabled again.
Not hard to do since jQuery already stores all of its event handlers as data() on the element itself. You can get (and modify) this object through .data().events.
Now you can easily save a reference to the handlers with:
events._click = events.click;
events.click = null;
And then restore them by using:
events.click = events._click;
events._click = null;
Note that this won't disable events that are bound via .delegate() or .live(), as they work by event bubbling/propagation. To disable those as well, simply bind a new handler that blocks propagation to ancestor elements:
events._click = events.click;
events.click = null;
// Block .live() and .delegate()
$("#el").click(function (e) {
e.stopPropagation();
});
You don't even need to unbind this blocker function when it's time to enable the handlers again, since events.click = events._click will override the function you just bound with all the old handlers.
Here is yet another way:
$("#myButton").click(function() {
if ($(this).attr("temp_disable") == "disabled") {
//nothing to do, temporarily disabled...
}
else {
alert("You clicked me!");
}
});
To "disable" it for 10 seconds:
$("#myButton").attr("temp_disable", "disabled");
window.setTimeout(function() { $("#myButton").attr("temp_disable", ""); }, 10000);
Live test case: http://jsfiddle.net/yahavbr/ByM6h/
That is the way to go. If you have onclick specified as an attribute you may switch the attribute busing
$(button_element).attr('click', '');
and
$(button_element).attr('click', 'do_the_regular_action()');
All answers here are now outdated - as of jQuery 1.7 you should use .off() as explained on the official jQuery site
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>off demo</title>
<style>
button {
margin: 5px;
}
button#theone {
color: red;
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button id="theone">Does nothing...</button>
<button id="bind">Add Click</button>
<button id="unbind">Remove Click</button>
<div style="display:none;">Click!</div>
<script>
function flash() {
$( "div" ).show().fadeOut( "slow" );
}
$( "#bind" ).click(function() {
$( "body" )
.on( "click", "#theone", flash )
.find( "#theone" )
.text( "Can Click!" );
});
$( "#unbind" ).click(function() {
$( "body" )
.off( "click", "#theone", flash )
.find( "#theone" )
.text( "Does nothing..." );
});
</script>
</body>
</html>
You can use unbind and bind
$('#control').unbind('click');
and
$('#control').bind('click', NameOfFunctionToCall);
I'll expand on the answer(s) offered by Barry and Thariama... which I think will satisfy Ovesh's objections:
You can add a namespace to your event binding. That lets you refer to that specific event binding later, without colliding with other bindings. I think this is cleaner than the accepted answer... (To be fair, this may not have been available in jQuery at the time of the original question).
// A generic click handler:
$('.myButton').click(function() { ... });
// A namespaced click handler:
$('.myButton').bind('click.someSituation', function() { ... });
// Later you can unbind only the handler you want by using the namespace:
$('.myButton').unbind('click.someSituation');
// The default click handler still works.
Instead of doing this thing Use Core Javascript to do this task
e.g. Look following example.
function MakeSaveDisabled(flg) {
if (flg != null) {
$(".btnpost").each(function () {
this.removeAttribute("disabled");
if (this.hasAttribute("oclickevt")) {
this.setAttribute("onclick", this.getAttribute("oclickevt"));
}
});
}
else {
$(".btnpost").each(function () {
this.setAttribute("disabled", "true");
if (this.getAttribute("onclick") != null) {
this.setAttribute("oclickevt", this.getAttribute("onclick"));
}
this.removeAttribute("onclick");
});
}
}
Save the javascript function in some temporary attribute and bind it when you required.
You can save the events and then restore them, this seems to work (note that the _ may need to be omitted depending on the version of JQuery).
This example stops the bootstrap toggle on-change event firing, then triggers the toggle then resets the events to whatever were there previously. You can do the same with click etc.
var events;
// Save change events associated with this control
events = $._data($(this)[0], "events").change;
$._data($(this)[0], "events").change = null;
// Do your stuff here
$(this).bootstrapToggle("off");
// Reset change events
$._data($(this)[0], "events").change = events;

jQuery how to bind onclick event to dynamically added HTML element [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I want to bind an onclick event to an element I insert dynamically with jQuery
But It never runs the binded function. I'd be happy if you can point out why this example is not working and how I can get it to run properly:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da">
<head>
<title>test of click binding</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
jQuery(function(){
close_link = $('<a class="" href="#">Click here to see an alert</a>');
close_link.bind("click", function(){
alert('hello from binded function call');
//do stuff here...
});
$('.add_to_this').append(close_link);
});
</script>
</head>
<body>
<h1 >Test of click binding</h1>
<p>problem: to bind a click event to an element I append via JQuery.</p>
<div class="add_to_this">
<p>The link is created, then added here below:</p>
</div>
<div class="add_to_this">
<p>Another is added here below:</p>
</div>
</body>
</html>
EDIT: I edited the example to contain two elements the method is inserted to. In that case, the alert() call is never executed. (thanks to #Daff for pointing that out in a comment)
All of these methods are deprecated. You should use the on method to solve your problem.
If you want to target a dynamically added element you'll have to use
$(document).on('click', selector-to-your-element , function() {
//code here ....
});
this replace the deprecated .live() method.
The first problem is that when you call append on a jQuery set with more than one element, a clone of the element to append is created for each and thus the attached event observer is lost.
An alternative way to do it would be to create the link for each element:
function handler() { alert('hello'); }
$('.add_to_this').append(function() {
return $('<a>Click here</a>').click(handler);
})
Another potential problem might be that the event observer is attached before the element has been added to the DOM. I'm not sure if this has anything to say, but I think the behavior might be considered undetermined.
A more solid approach would probably be:
function handler() { alert('hello'); }
$('.add_to_this').each(function() {
var link = $('<a>Click here</a>');
$(this).append(link);
link.click(handler);
});
How about the Live method?
$('.add_to_this a').live('click', function() {
alert('hello from binded function call');
});
Still, what you did about looks like it should work. There's another post that looks pretty similar.
A little late to the party but I thought I would try to clear up some common misconceptions in jQuery event handlers. As of jQuery 1.7, .on() should be used instead of the deprecated .live(), to delegate event handlers to elements that are dynamically created at any point after the event handler is assigned.
That said, it is not a simple of switching live for on because the syntax is slightly different:
New method (example 1):
$(document).on('click', '#someting', function(){
});
Deprecated method (example 2):
$('#something').live(function(){
});
As shown above, there is a difference. The twist is .on() can actually be called similar to .live(), by passing the selector to the jQuery function itself:
Example 3:
$('#something').on('click', function(){
});
However, without using $(document) as in example 1, example 3 will not work for dynamically created elements. The example 3 is absolutely fine if you don't need the dynamic delegation.
Should $(document).on() be used for everything?
It will work but if you don't need the dynamic delegation, it would be more appropriate to use example 3 because example 1 requires slightly more work from the browser. There won't be any real impact on performance but it makes sense to use the most appropriate method for your use.
Should .on() be used instead of .click() if no dynamic delegation is needed?
Not necessarily. The following is just a shortcut for example 3:
$('#something').click(function(){
});
The above is perfectly valid and so it's really a matter of personal preference as to which method is used when no dynamic delegation is required.
References:
jQuery docs for .on()
jQuery docs for .click()
jQuery docs for .live()
Consider this:
jQuery(function(){
var close_link = $('<a class="" href="#">Click here to see an alert</a>');
$('.add_to_this').append(close_link);
$('.add_to_this').children().each(function()
{
$(this).click(function() {
alert('hello from binded function call');
//do stuff here...
});
});
});
It will work because you attach it to every specific element. This is why you need - after adding your link to the DOM - to find a way to explicitly select your added element as a JQuery element in the DOM and bind the click event to it.
The best way will probably be - as suggested - to bind it to a specific class via the live method.
It is possible and sometimes necessary to create the click event along with the element. This is for example when selector based binding is not an option. The key part is to avoid the problem that Tobias was talking about by using .replaceWith() on a single element. Note that this is just a proof of concept.
<script>
// This simulates the object to handle
var staticObj = [
{ ID: '1', Name: 'Foo' },
{ ID: '2', Name: 'Foo' },
{ ID: '3', Name: 'Foo' }
];
staticObj[1].children = [
{ ID: 'a', Name: 'Bar' },
{ ID: 'b', Name: 'Bar' },
{ ID: 'c', Name: 'Bar' }
];
staticObj[1].children[1].children = [
{ ID: 'x', Name: 'Baz' },
{ ID: 'y', Name: 'Baz' }
];
// This is the object-to-html-element function handler with recursion
var handleItem = function( item ) {
var ul, li = $("<li>" + item.ID + " " + item.Name + "</li>");
if(typeof item.children !== 'undefined') {
ul = $("<ul />");
for (var i = 0; i < item.children.length; i++) {
ul.append(handleItem(item.children[i]));
}
li.append(ul);
}
// This click handler actually does work
li.click(function(e) {
alert(item.Name);
e.stopPropagation();
});
return li;
};
// Wait for the dom instead of an ajax call or whatever
$(function() {
var ul = $("<ul />");
for (var i = 0; i < staticObj.length; i++) {
ul.append(handleItem(staticObj[i]));
}
// Here; this works.
$('#something').replaceWith(ul);
});
</script>
<div id="something">Magical ponies ♥</div>
function load_tpl(selected=""){
$("#load_tpl").empty();
for(x in ds_tpl){
$("#load_tpl").append('<li><a id="'+ds_tpl[x]+'" href="#" >'+ds_tpl[x]+'</a></li>');
}
$.each($("#load_tpl a"),function(){
$(this).on("click",function(e){
alert(e.target.id);
});
});
}
I believe the good way it to do:
$('#id').append('<a id="#subid" href="#">...</a>');
$('#subid').click( close_link );
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click', '.close', function(){
var rowid='row'+this.id;
var sl = '#tblData tr[id='+rowid+']';
console.log(sl);
$(sl).remove();
});
$("#addrow").click(function(){
var row='';
for(var i=0;i<10;i++){
row=i;
row='<tr id=row'+i+'>'
+ '<td>'+i+'</td>'
+ '<td>ID'+i+'</td>'
+ '<td>NAME'+i+'</td>'
+ '<td><input class=close type=button id='+i+' value=X></td>'
+'</tr>';
console.log(row);
$('#tblData tr:last').after(row);
}
});
});
</script>
</head>
<body>
<br/><input type="button" id="addrow" value="Create Table"/>
<table id="tblData" border="1" width="40%">
<thead>
<tr>
<th>Sr</th>
<th>ID</th>
<th>Name</th>
<th>Delete</th>
</tr>
</thead>
</table>
</body>
</html>

Categories

Resources