Monday, June 11, 2012

Getting the ID of the element that fired an event using JQuery


Is there any way to get the ID of the element that fires an event?



I'm thinking something like:




<html>
<head>
<script type="text/javascript" src="starterkit/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("a").click(
function(){
var test = caller.id;
alert(test.val());
}
);
});

</script>
</head>
<body>
<form class="item" id="aaa"><input class="title"></input></form>
<form class="item" id="bbb"><input class="title"></input></form>
</body>
</html>



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.



Can anyone help with this?


Source: Tips4all

5 comments:

  1. In jQuery event.target always refers to the element that triggered the event, where 'event' is the parameter passes to the function. http://docs.jquery.com/Events_(Guide)

    $(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");
    });
    });

    ReplyDelete
  2. You can use (this) to reference the object the 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.

    ReplyDelete
  3. I'm a tad late. lol. For reference, try this! It works!

    jQuery("classNameofDiv").click(function() {
    var contentPanelId = jQuery(this).attr("id");
    alert(contentPanelId);

    });

    ReplyDelete
  4. 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);
    });

    ReplyDelete
  5. 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);
    });

    ReplyDelete