0

I have JQuery included and all my other click functions work. I have tried to debug and change it from class to ID and both the class and ID name is unique (no other element uses the class or ID).

<button type="button" style="margin-left: 5px; padding: 7px;" class="btn query-btn"> Search Transactions </button>

Here is my code for the HTML and my JQuery is:

 $(".query-btn").click(function () {
            alert("gets here");
 });

I literally have no idea why this isn't working because it works on everything else. Could anyone possibly point me the right direction? I have tried giving it an ID (unique) and changing the . to a # and that does not work either and yes it is wrapped in a:

$(document).ready(function () {

I receive no errors which is what is sort of confusing me. Anything would be appreciated!

Note: The HTML button is actually added by AJAX (A button is pressed and the response is directly inserted using the innerHTML), not default page load. I'm not sure if this would effect it but just a note incase it does.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Jaquarh
  • 6,493
  • 7
  • 34
  • 86

1 Answers1

4

If the button is added by Ajax then you need to use on and an enclosing selector, roughly:

$('body').on('click', '.query-btn', function () {
    // Whatever
});

(I'm using body as an example selector, ideally you'd scope it to something much smaller.)

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • Perfect! Would I be able to find documentation on this? (I am guessing I search for JQuery `on`?) I have never seen this before, I'll mark the answer when I can. Thanks again! - Also, thanks for the edit. – Jaquarh Feb 29 '16 at 14:37
  • 1
    @KyleE4K It's called event delegation. Have a look at this [link](https://learn.jquery.com/events/event-delegation/) – empiric Feb 29 '16 at 14:38
  • 1
    Please don't answer such **obvious dupes**, if you cannot add things to it. Close them. – Tushar Feb 29 '16 at 14:39
  • 1
    @Tushar Was on phone; will search for dupe in a few. I'd rather askers had something to work with sooner than later. – Dave Newton Feb 29 '16 at 14:40
  • If it is a duplicate, vote to close it. But I wouldn't of made a question if I couldn't find the answer @Tushar Its apparent that I did not know the `on` statement/event existed and everything I searched was literlly silly things like, they forgot to actually import JQuery or use the `$(document).ready` function. But for future reference, I'll try search harder :) Thanks again though! – Jaquarh Feb 29 '16 at 14:42