简体   繁体   中英

Detect which dropdown box was clicked in jquery

I am executing the same function on multiple dropdown boxes with id: assignee, status , priority .

$("#assignee , #status , #priority").change(function() { 

//text here

}

But I want to know which specific dropdown was clicked. Is there any method to do this?

Simply use the following:

$("#assignee, #status, #priority").change(function() { 
    if (this.id === "assignee") { ... }
});

Use this. In any event handler this points to an element where actual event happened:

$("#assignee , #status , #priority").change(function() { 
    var changedElementID = $(this).attr("id");
}

Another option is to use event.target :

$("#assignee , #status , #priority").change(function(e) { 
        var changedElementID = $(e.target).attr("id");
    }

And here you can find more detailed information about other event object properties.

Note that both this and e.target are DOM objects, not jQuery objects. So you need to wrap it with jquery like in my code above to use jQuery functions. If simply get an id - you can use directly this.id or e.target.id which is faster.

When the event is triggered, inside the event handler function this refers to the element that triggered the event, so:

$('#assignee, #status, #priority').change(function(e) {
    // Use 'this' to refer to the element that triggered the event
    console.log(this.id);
    // will output assignee, status or priority depending on which changed
});

Use target :

$("#assignee , #status , #priority").change(function(e) { 
        var changedElementID = $(e.target).attr("id");
    }

Where you are binding your <option> at that point pass this to the function and use your own code

$("#assignee , #status , #priority").change(function(boxID) { 
console.log($(boxID).val());    //Gives you the value of the selected drop down


//text here

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM