0

I have a situation where I need to bind an onclick event to a button which is being dynamically injected into the main html document by an external JavaScript.

The problem is that that the class id of the button is suffixed with some dynamic numbers which change every time the page is reloaded.

Please see example:

<button class="clickme12345" type=submit value=clickme>send</button> 

Now the situation is that on every page reload the numbers for the class id for the button will change so next time it will be clickme67890.

Would there be any way to get the jQuery binding to work for this situation?

Any reply would be greatly appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
bob dabelina
  • 507
  • 5
  • 20
  • 1
    please include relevant code or replicate the said sample in snippet – guradio Oct 17 '15 at 02:14
  • it's really not that complicated of a code, it's something like: , so the situation is that on every page reload the numbers for the class id for the button will change so next time it will be clickme67890. – bob dabelina Oct 17 '15 at 02:17
  • 1
    bind the event to the parent element and let it bubble, use a css selector to specify the target of the event. $('parent').on('click', 'button_css_selector', handler); – Dayan Moreno Leon Oct 17 '15 at 02:18
  • 1
    Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Renato Zannon Oct 17 '15 at 02:18
  • It's not a duplicate, in my example the class id is not static but it also changes. Please see example in previous comments. – bob dabelina Oct 17 '15 at 02:21
  • Dayan Moreno Leon, I don't really understand your explanation. can yo please elaborate. Just wanted to confirm also that the class id of the button is not static and changes every single time. – bob dabelina Oct 17 '15 at 02:23
  • @bobdabelina please include the code which your changing the `class` on page load – jlocker Oct 17 '15 at 02:38
  • @jlocker, it's an external java script. It's not my code. – bob dabelina Oct 17 '15 at 02:40

1 Answers1

0

If this is really how you want to use it, you could use an attribute selector

Something like [attr*=value] where the attr contains the string value.

For example (in jQuery):

var $btnElement = $('[class*="clickme"]');

The above will select any elements that have a class attribute containing clickme

Mr. Meeseeks
  • 1,841
  • 2
  • 21
  • 37