I have looked at the .on() | jQuery API Documentation for help with my particular use-case but I couldn't find the information on how to do it or if it can even be done.
I would like to attach a function to an event (say click) for two different "selectors", like this:
- one:
'div[id^="action_"]'
- second:
'div[id^="user_"]'
I have tried all the below combinations based on how jQuery normally handles multiples of things but some just don't work and the others will only process the first selector and ignore the second altogether:
// correct
$(document).on("click", 'div[id^="action_"], div[id^="user_"]' , function(){
// incorrect
$(document).on("click", 'div[id^="action_"] div[id^="user_"]' , function(){
$(document).on("click", 'div[id^="action_"]' || 'div[id^="user_"]' , function(){
$(document).on("click", 'div[id^="action_"]', 'div[id^="user_"]' , function(){
The first was what I was sure would work and when it didn't, led me to try everything else as clearly a shot in the dark attempt. Of the ones now marked incorrect, first one simply doesn't do anything, second and third one both result in the first being handled but not the second. The last one I was pretty sure doesn't work and I didn't expect it to, since it holds the [,data]
portion of the syntax but for sake of completeness, tried it.
- Am I simply overlooking something as simple as syntax here?
- Or, can this simply not be done as-is?
- Now clear that it works but something else might be interfering!
any help on this would be greatly appreciated before I just go ahead and split them into two pieces of code which would be ugly and messy. TIA.
Resolution
Thanks to Frank's answer and kind fiddles, it was confirmed that my initial instinct as shown on line one of the tried methods was correct (I have updated it to show more clearly what is correct and not). I am still not certain why it didn't work as expected which led me to post the question but I suspect that the problem probably arose from GM and/or possible interference from something on the page itself, and not the code. If I find out the exact source of the observation, I will edit this to reflect it for sake of completeness.
See Question&Answers more detail:os