0

I have some code where I add a button dynamically to the page.

<a href=“#1" class="btn btn-default next">Next</a>

I am using the .on() method with the selector parameter but nothing is happening when I click the button. I saw that other people had a similar problem for dynamically added elements but they were missing the selector and adding it solved it.

$(".next").on("click", ".next", function() {

    alert(“next page");

});

I've put the button in the main body of my page when it loads and it works fine. It just doesn't work when it gets added to the page later.

4 Answers4

0

Change

$(".next").on("click", ".next", function() {

to

$(document).on("click", ".next", function() {

Since you are dynamically creating the elements, using document will delegate the events on to the children elements so this helps to bubble up events on document level.

Aditya
  • 1,213
  • 5
  • 18
  • 29
0

Let us suppose that ancestor is the selector of an ancestor of the button in your html. Then:

$(ancestor).on("click", ".next", function() {
    alert("I have clicked on the button");
});

This works even if your button does not exist when this part runs. If you have nothing more specific for ancestor, then you can use "body".

Lajos Arpad
  • 45,912
  • 26
  • 82
  • 148
0

Try this

You can use document or body

$(document).on("click",".next", function() {
alert('button clicked');
});
I'm Geeker
  • 4,642
  • 5
  • 19
  • 40
0

use can use onClick property of html

function myFunction()
{
    alert("hello");
}
<button onclick="myFunction()">Click me</button>
Vaibhav Raut
  • 462
  • 3
  • 11