Getting the ID of the element that fired an event - javascript

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.

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>

JQuery - Get the ID attribute of li element

I have a pagination control who's <li> elements are dynamically set and assigned a ID. Using jQuery I am then attempting ti retrieve these set ID's
<div class="col-lg-12 text-center">
<ul class="pagination" id="pagHolder"></ul>
</div>
<script>
$(document).ready(function () {
//*****Logic for setting 'mainArrayHolder'*****
for(var i = 0; t < mainArrayHolder.length; i++)
{
$('#pagHolder').append('<li id="'+i+'">'+ i +'</li>');
}
});
</script>
The Issue I have is I am receiving an 'undefined' error when using the following function:
$(this).click(function(){
var id = $(this).attr("id");
alert(id);
});
I understand this is because 'this' is looking at the whole of the DOM rather than just the <li> elements. How do I set this code so it will get the id attribute of any of the <li> elements a user clicks?
You need to update the selector for your click event.
The following should work:
$('#pagHolder').on('click', 'li', function() {
alert( $(this).attr('id') );
});
Notice that we use the on() function, and delegate the event to any li which exists now (or in the future) as a child node of pagHolder.
Alternatively, you don't need to use jQuery's attr() function inside of the event handler, since this relates to the DOM node itself, you can access its properties directly, for example:
$('#pagHolder').on('click', 'li', function() {
alert( this.id );
});
You are appending li's to #pagHolder list, so you could get ids like this, for example:
$('#pagHolder').on('click', 'li', function() {
var id = this.id;
alert(id);
});

Find Id of clicked button

I wanted to get the id of clicked button since i have 4-5 buttons on my form.
<button type="submit" style="height: 30px" id="btnHelp" name="btnHelp" onclick="ShowHelp(2);return false;">Help</button>
<button type="button" style="height: 30px" id="btnClose" name="btnClose" onclick="Close();return false;">Close</button>
<button type="button" style="height: 30px" id="btnSave" name="btnSave" onclick="Save();return false;">Close</button>
...............................
Whichever may be the button click, I just want to get id of that button.
$(function () {
var id = $(this).attr('id');
alert(id);
})
Also with
$("input").click(function (event) {
var urlid = $(this).attr('id')
alert(urlid);
})
but i am getting the alert as undefined.
How can i get id of button clicked?
Please help me.
Try
:button Selector
Selects all button elements and elements of type button.
$(":button").click(function (event) {
var urlid = this.id;
alert(urlid);
});
Fiddle Demo
Problem
$("input") --> selects elements with tag input eg. <input type="text"/> but not <button> tag .
I'd try to replace this with the event triggerer.
var urlid = $(event.target).attr("id");
Also, probably your onclick function is preventing your script to be executed, because it's handling the click event, not letting your function do it.
I ditched the onclick attributes of buttons you have, and hooked click events to button rather than input, and it worked. So check whether you are connecting to the right element.
See example here.
<script>
jQuery(":button").click(function (event) {
var urlid = $(this).attr('id')
alert(urlid);
})
</script>
Try this its work
very simply:
$("input").click(function (event) {
var urlid = this.id;
alert(urlid);
})
for button:
$("button").click(function (event) {
var urlid = this.id;
alert(urlid);
})
You might try use event passed as argument into any event handler instead of this for event.target is referring to element actually triggering your handler (being clicked) and event.delegateTarget being element handler has been attached to initially. In both cases you might have to use $() for using jQuery or simply stick with accessing .id in either case.
In your case this would be
$("input").click(function (event) {
var urlid = $(event.delegateTarget).attr('id');
alert(urlid);
});
to ensure handler is always accessing that it has been attached to, here.
Except for this quite simple scenario relying on this is sometimes trickier than using provided arguments.
EDIT : However, your case seems to be related to issues encountered by Tusha Gupta, for sure. Your buttons aren't "inputs" so that handlers are never attached, actually.
$(function () {
$("button").click(function () {
alert($(this).attr("id"));
});
});

How to decide which element is being clicked in jQuery?

I have more similar elements in HTML which are being added continously with PHP. my question is the following:
With jQuery, I would like to add a click event to each of these <div> elements. When any of them is being clicked it should display it's content. The problem is that I guess I need to use classes to specify which elements can be clickable. But in this case the application will not be able to decide which specific element is being clicked, right?
HTML:
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>
jQuery try:
$("test").on("click", function()
{
var data = ???
alert(data);
});
UPDATE - QUESTION 2:
What happens if I'm placing <a> tags between those divs, and I want to get their href value when the DIV is being clicked?
I always get an error when I try that with this.
this refers to the element triggering the event. Note that it is a regular js element, so you'll need to convert it to a jQuery object before you can use jQuery functions: $(this)
$(".test").on("click", function()
{
var data = $(this).text();
alert(data);
});
Like this:
$(".test").on("click", function(event)
{
var data = $(event.target);
alert(data.text());
});
this variable contains the reference of current item
$(document).ready(function() {
$(".test").click(function(event) {
var data = $(this).text();
alert(data);
});
})
;
The class selector in jquery is $(".ClassName") and to access the value, use $(this) as such:
$(".test").on("click", function(){
var data = $(this).text();
alert(data);
});
You can use this inside the function which mean clicked div
DEMO
$(".test").on("click", function () {
alert($(this).html());
});

How to refactor this simple code

I have a following script:
$(document).ready(function() {
$('#q1_6').on("click", function(event){
$('#q1-f').slideToggle(350);
});
$('#q1_7').on("click", function(event){
$('#q1-m').slideToggle(350);
});
$('#q1_15').on("click", function(event){
$('#q1-o').slideToggle(350);
});
$('#q2_6').on("click", function(event){
$('#q2-f').slideToggle(350);
});
$('#q2_7').on("click", function(event){
$('#q2-m').slideToggle(250);
});
$('#q2_15').on("click", function(event){
$('#q2-o').slideToggle(350);
});
$('#q3_13').on("click", function(event){
$('#q3-o').slideToggle(350);
});
});
Are these calls proper, or maybe I should somehow refactor the script to avoid duplication?
Edit:
I am creating a survey with about 20 questions displayed on one page. Answers are in checkboxes. Some answers have additional options (sub-answers), which should be shown when user clicks parental answer. Here is HTML markup for better understanding
<div>
<input type="checkbox" id="q1_5"/><label for="q1_5">Answer 5</label>
</div>
<div>
<input type="checkbox" id="q1_6"/><label for="q1_6">Answer 6</label>
</div>
<div id="q1-f">
<div>
<input type="checkbox" id="q1_6_1"/><label for="q1_6_1">Answer 6-1</label>
</div>
<div>
<input type="checkbox" id="q1_6_2"/><label for="q1_6_2">Answer 6-2</label>
</div>
<div>
<input type="checkbox" id="q1_6_3"/><label for="q1_6_3">Answer 6-3</label>
</div>
</div>
Current script works well, but I am wondering if I can avoid repeats of the same code snippets.
If you have access to the HTML and can influence the structure of the elements which when clicked initiate the toggle, then I'd add a class and data attribute:
<a href='#' id='q1_6' class='toggle' data-toggle-id='q1-f'>blah</a>
$(document).ready(function() {
$('a.toggle').on('click', function(){
var $el = $(this),
toggleID = '#' + $el.attr('data-toggle-id'),
toggleValue = 350;
$(toggleID).slideToggle(toggleValue);
});
});
given no idea on how IDs are correlated in your example.
function toggle(id, id2, value){
$(id).on("click", function(event){
$(id2).slideToggle(value);
});
}
toggle('#q1_15', '#q1-0', 350);
You could do :
$('[id^="q"]').on("click", function(e){
//get the id of the clicked button
var id = e.target.id;
switch(id){
//do all cases based on id
}
});
This could be done in an even cleaner way if there is some element to which we could delegate the event handling, but you didn't show us your markup. It would be something like
$('body').on("click",'[id^="q"]', function(e){
//get the id of the clicked button
var id = e.target.id;
switch(id){
//do all cases based on id
}
});
This second option use only one event handler (good) but it has to wait until the event is bubbled up the DOM (might be bad)
Why don't you create a javascript object where keys denote the id of element that accepts clicks and corresponding value is the id of element to show. Something like:
var clickHanders = {
"q1_6": "q1-f",
"q1_7": "q1-m"
// ...
};
Then all you need is:
$(document).ready(function() {
$("div[id^=q]").on("click", function(event) {
var srcId = this.id;
var dstId = clickHanders[srcId];
if (dstId) {
$("#" + dstId).slideToggle(350);
}
});
});
Edit
I now see that the slide duration can be different as well. You can still use the above approach:
var clickHanders = {
"q1_6": {
"elementId": "q1-f",
"duration": "350"
},
"q2_7": {
"elementId": "q2-m",
"duration": "250"
}
//...
};
$(document).ready(function() {
$("div[id^=q]").on("click", function(event) {
var srcId = this.id;
var dstData = clickHanders[srcId];
if (dstData) {
$("#" + dstData.elementId).slideToggle(dstData.duration);
}
});
});
This code looks longer than your original code but perhaps more sensible.
There are some things to ask when you refactor:
Are you having speed problems?
Are you having memory problems?
Does the code look ugly?
You should not be refactoring code just to refactor it and optimize something where it is not needed. If the code is not too slow and does not have a too high memory consumption (all in the eye of the beholder) and is readable, you have good code.
My idea would be to serialize the event trigger, event target and slideToggle amount, so you could iterate through some kind of Collection and bind it. But would that be worth it?
Well, each handler does the very same thing, so here's what you should do:
Refactor your HTML, for example:
<div id="q1-6" data-to="q1-f"></div>
for each object (you can use other HTML attributes). Then you can define handlers:
$('#q1-6,#q1-7,#someother_id,#watman,#foo').click(function() {
var id = $(this).attr('data-to');
$('#'+id).slideToggle(350);
});
There is no way to shorten your code, because there is nothing exactly the same, so your code is ok.

Categories

Resources