add event for sub children in jquery - javascript

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/

Related

Element calling old action after class change [duplicate]

In my JSP page I added some links:
<a class="applicationdata" href="#" id="1">Organization Data</a>
<a class="applicationdata" href="#" id="2">Business Units</a>
<a class="applicationdata" href="#" id="6">Applications</a>
<a class="applicationdata" href="#" id="15">Data Entity</a>
It has a jQuery function registered for the click event:
$("a.applicationdata").click(function() {
var appid = $(this).attr("id");
$('#gentab a').addClass("tabclick");
$('#gentab a').attr('href', '#datacollector');
});
It will add a class, tabclick to <a> which is inside <li> with id="gentab". It is working fine. Here is my code for the <li>:
<li id="applndata"><a class="tabclick" href="#appdata" target="main">Application Data</a></li>
<li id="gentab">General</li>
Now I have a jQuery click handler for these links
$("a.tabclick").click(function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
For the first link it is working fine. It is alerting the <li> id. But for the second <li>, where the class="tabclick" is been added by first jQuery is not working.
I tried $("a.tabclick").live("click", function(), but then the first link click event was also not working.
Since the class is added dynamically, you need to use event delegation to register the event handler
$(document).on('click', "a.tabclick", function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
You should use the following:
$('#gentab').on('click', 'a.tabclick', function(event) {
event.preventDefault();
var liId = $(this).closest("li").attr("id");
alert(liId);
});
This will attach your event to any anchors within the #gentab element,
reducing the scope of having to check the whole document element tree and increasing efficiency.
.live() is deprecated.When you want to use for delegated elements then use .on() wiht the following syntax
$(document).on('click', "a.tabclick", function() {
This syntax will work for delegated events
.on()
Based on #Arun P Johny this is how you do it for an input:
<input type="button" class="btEdit" id="myButton1">
This is how I got it in jQuery:
$(document).on('click', "input.btEdit", function () {
var id = this.id;
console.log(id);
});
This will log on the console: myButton1.
As #Arun said you need to add the event dinamically, but in my case you don't need to call the parent first.
UPDATE
Though it would be better to say:
$(document).on('click', "input.btEdit", function () {
var id = $(this).id;
console.log(id);
});
Since this is JQuery's syntax, even though both will work.
on document ready event there is no a tag with class tabclick. so you have to bind click event dynamically when you are adding tabclick class. please this code:
$("a.applicationdata").click(function() {
var appid = $(this).attr("id");
$('#gentab a').addClass("tabclick")
.click(function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
$('#gentab a').attr('href', '#datacollector');
});
Here is the another solution as well, the bind method.
$(document).bind('click', ".intro", function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
Cheers :)
I Know this is an old topic...but none of the above helped me.
And after searching a lot and trying everything...I came up with this.
First remove the click code out of the $(document).ready part and put it in a separate section.
then put your click code in an $(function(){......}); code.
Like this:
<script>
$(function(){
//your click code
$("a.tabclick").on('click',function() {
//do something
});
});
</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>

Ajax function doesn't work with dynamic div

My function for onclick is:
$(document).ready(function() {
$('.mydata').click(function() {
alert($(this).attr('data'));
});
});​
A static element will work:
<div><span id='moreinfo' class='mydata' data="25">Click Me!</span></div>
<div><span id='moreinfo' class='mydata' data="250">Click Me Too!</span></div>
But a div pair populated with the same elements dynamically will not fire off the function. What am I doing wrong?
Code example at: http://jsfiddle.net/KubXr/
you need event delegation:
$(function(){
$(document).on('click', '.mydata', function() {
alert($(this).attr('data'));
});
});
this means that, any element, existing or future, dynamically added, will have the event triggered if contains the mydata class.

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>

Getting the ID of the element that fired an event

Is there any way to get the ID of the element that fires an event?
I'm thinking something like:
$(document).ready(function() {
$("a").click(function() {
var test = caller.id;
alert(test.val());
});
});
<script type="text/javascript" src="starterkit/jquery.js"></script>
<form class="item" id="aaa">
<input class="title"></input>
</form>
<form class="item" id="bbb">
<input class="title"></input>
</form>
Except of course that the var test should contain the id "aaa", if the event is fired from the first form, and "bbb", if the event is fired from the second form.
In jQuery event.target always refers to the element that triggered the event, where event is the parameter passed to the function. http://api.jquery.com/category/events/event-object/
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});
Note also that this will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as $(this), e.g.:
$(document).ready(function() {
$("a").click(function(event) {
// this.append wouldn't work
$(this).append(" Clicked");
});
});
For reference, try this! It works!
jQuery("classNameofDiv").click(function() {
var contentPanelId = jQuery(this).attr("id");
alert(contentPanelId);
});
Though it is mentioned in other posts, I wanted to spell this out:
$(event.target).id is undefined
$(event.target)[0].id gives the id attribute.
event.target.id also gives the id attribute.
this.id gives the id attribute.
and
$(this).id is undefined.
The differences, of course, is between jQuery objects and DOM objects. "id" is a DOM property so you have to be on the DOM element object to use it.
(It tripped me up, so it probably tripped up someone else)
For all events, not limited to just jQuery you can use
var target = event.target || event.srcElement;
var id = target.id
Where event.target fails it falls back on event.srcElement for IE.
To clarify the above code does not require jQuery but also works with jQuery.
You can use (this) to reference the object that fired the function.
'this' is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.
Here is where you can learn more: http://remysharp.com/2007/04/12/jquerys-this-demystified/
I generate a table dynamically out a database, receive the data in JSON and put it into a table. Every table row got a unique ID, which is needed for further actions, so, if the DOM is altered you need a different approach:
$("table").delegate("tr", "click", function() {
var id=$(this).attr('id');
alert("ID:"+id);
});
Element which fired event we have in event property
event.currentTarget
We get DOM node object on which was set event handler.
Most nested node which started bubbling process we have in
event.target
Event object is always first attribute of event handler, example:
document.querySelector("someSelector").addEventListener(function(event){
console.log(event.target);
console.log(event.currentTarget);
});
More about event delegation You can read in http://maciejsikora.com/standard-events-vs-event-delegation/
The source element as a jQuery object should be obtained via
var $el = $(event.target);
This gets you the source of the click, rather than the element that the click function was assigned too. Can be useful when the click event is on a parent object
EG.a click event on a table row, and you need the cell that was clicked
$("tr").click(function(event){
var $td = $(event.target);
});
this works with most types of elements:
$('selector').on('click',function(e){
log(e.currentTarget.id);
});
You can try to use:
$('*').live('click', function() {
console.log(this.id);
return false;
});
Use can Use .on event
$("table").on("tr", "click", function() {
var id=$(this).attr('id');
alert("ID:"+id);
});
In the case of delegated event handlers, where you might have something like this:
<ul>
<li data-id="1">
<span>Item 1</span>
</li>
<li data-id="2">
<span>Item 2</span>
</li>
<li data-id="3">
<span>Item 3</span>
</li>
<li data-id="4">
<span>Item 4</span>
</li>
<li data-id="5">
<span>Item 5</span>
</li>
</ul>
and your JS code like so:
$(document).ready(function() {
$('ul').on('click li', function(event) {
var $target = $(event.target),
itemId = $target.data('id');
//do something with itemId
});
});
You'll more than likely find that itemId is undefined, as the content of the LI is wrapped in a <span>, which means the <span> will probably be the event target. You can get around this with a small check, like so:
$(document).ready(function() {
$('ul').on('click li', function(event) {
var $target = $(event.target).is('li') ? $(event.target) : $(event.target).closest('li'),
itemId = $target.data('id');
//do something with itemId
});
});
Or, if you prefer to maximize readability (and also avoid unnecessary repetition of jQuery wrapping calls):
$(document).ready(function() {
$('ul').on('click li', function(event) {
var $target = $(event.target),
itemId;
$target = $target.is('li') ? $target : $target.closest('li');
itemId = $target.data('id');
//do something with itemId
});
});
When using event delegation, the .is() method is invaluable for verifying that your event target (among other things) is actually what you need it to be. Use .closest(selector) to search up the DOM tree, and use .find(selector) (generally coupled with .first(), as in .find(selector).first()) to search down it. You don't need to use .first() when using .closest(), as it only returns the first matching ancestor element, while .find() returns all matching descendants.
This works on a higher z-index than the event parameter mentioned in above answers:
$("#mydiv li").click(function(){
ClickedElement = this.id;
alert(ClickedElement);
});
This way you will always get the id of the (in this example li) element. Also when clicked on a child element of the parent..
$(".classobj").click(function(e){
console.log(e.currentTarget.id);
})
var buttons = document.getElementsByTagName('button');
var buttonsLength = buttons.length;
for (var i = 0; i < buttonsLength; i++){
buttons[i].addEventListener('click', clickResponse, false);
};
function clickResponse(){
// do something based on button selection here...
alert(this.id);
}
Working JSFiddle here.
Just use the this reference
$(this).attr("id")
or
$(this).prop("id")
this.element.attr("id") works fine in IE8.
Pure JS is simpler
aaa.onclick = handler;
bbb.onclick = handler;
function handler() {
var test = this.id;
console.log(test)
}
aaa.onclick = handler;
bbb.onclick = handler;
function handler() {
var test = this.id;
console.log(test)
}
<form class="item" id="aaa">
<input class="title"/>
</form>
<form class="item" id="bbb">
<input class="title"/>
</form>
Both of these work,
jQuery(this).attr("id");
and
alert(this.id);
You can use the function to get the id and the value for the changed item(in my example, I've used a Select tag.
$('select').change(
function() {
var val = this.value;
var id = jQuery(this).attr("id");
console.log("value changed" + String(val)+String(id));
}
);
I'm working with
jQuery Autocomplete
I tried looking for an event as described above, but when the request function fires it doesn't seem to be available. I used this.element.attr("id") to get the element's ID instead, and it seems to work fine.
In case of Angular 7.x you can get the native element and its id or properties.
myClickHandler($event) {
this.selectedElement = <Element>$event.target;
console.log(this.selectedElement.id)
this.selectedElement.classList.remove('some-class');
}
html:
<div class="list-item" (click)="myClickHandler($event)">...</div>
There's plenty of ways to do this and examples already, but if you need take it a further step and need to prevent the enter key on forms, and yet still need it on a multi-line textarea, it gets more complicated. The following will solve the problem.
<script>
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
//There are 2 textarea forms that need the enter key to work.
if((event.target.id=="CommentsForOnAir") || (event.target.id=="CommentsForOnline"))
{
// Prevent the form from triggering, but allowing multi-line to still work.
}
else
{
event.preventDefault();
return false;
}
}
});
});
</script>
<textarea class="form-control" rows="10" cols="50" id="CommentsForOnline" name="CommentsForOnline" type="text" size="60" maxlength="2000"></textarea>
It could probably be simplified more, but you get the concept.
Simply you can use either:
$(this).attr("id");
Or
$(event.target).attr("id");
But $(this).attr("id") will return the ID of the element to which the Event Listener is attached to.
Whereas when we use $(event.target).attr("id") this will return the ID of the element that was clicked.
For example in a <div> if we have a <p> element then if we click on 'div' $(event.target).attr("id") will return the ID of <div>, if we click on 'p' then $(event.target).attr("id") will return ID of <p>.
So use it as per your need.

Categories

Resources