Get element on event with jquery

What If we apply an event on multiple element? Yes in this post we are talking about to get the element on particular event. Let’s say we have more then one element and on these elements we want the click event. But now how do we detect the clicked element. In the given example, i just talking two input fields, with different name and id. And apply the click event on both elements.

Here is the HTML Example:

<div id="container">
<label>Field One: </label><input type="text" name="tbox" id="mybox" size="30" /><br />
<label>Field Two: </label><input type="text" name="tbox2" id="mybox2" size="30" />
</div>

 

Now simply get the element id or element name on click event. Like according to the below codes you can easily get the id of the element and the name of the element on the click event.

$(function() {
    $('input[name="tbox"], input[name="tbox2"]').click(function(e){
        var element_id, element_name;

        element_id = e.target.id; // Get the ID of the Element
        element_name = e.target.name; // Get the Name of the Element

 

You don’t need to taking the both of the element, but if necessary then you can. Now put any one of the variable into the switch statement, yes we will detect the name on the click event and taking the action with the switch and case statement, like the below Example:

$(function() {
    $('input[name="tbox"], input[name="tbox2"]').click(function(e){
        var element_id, element_name;

        //element_id = e.target.id; // Get the ID of the Element
        element_name = e.target.name; // Get the Name of the Element

        switch( element_name ) {
          case 'tbox':
            alert('Clicked on Field One!');
          break;
          case 'tbox2':
            alert('Clicked on Field Two!');
          break;
      }

    });
})

 

This is the complete set of code, Please let me know for the updates or any kind of bug in the comments section..

Posted by Jogesh Sharma

Jogesh Sharma is a web developer and blogger who loves all the things design and the technology, He love all the things having to do with PHP, WordPress, Joomla, Magento, Durpal, Codeigniter, jQuery, HTML5 etc. He is the author of this blog.