1

guys, currently I'm working on a project where I need to load some data through AJAX. I'm using jQuery for AJAX. Here are the HTML and JavaScript code

<body>
<input type="submit" value="Number 1">
<script src="jquery.js"></script>
<script>
    $(document).ready(function(){
        $.ajax('ajax.html',{
        success: function(data){
            $('body').append(data);
        }
        });

        $('input').click(function(){
            alert('bang!!!');
        });
     });
 </script>
</body>

And here is the ajax.html file

<input type="submit" value="Number 2">

Now the AJAX is working perfectly, but the click event is not working with the AJAX loaded input tag

The click event is working perfectly with the first input tag

  • See here: https://stackoverflow.com/questions/16598213/how-to-bind-events-on-ajax-loaded-content – Donal Sep 27 '17 at 11:14
  • just look at this:https://stackoverflow.com/questions/9122078/difference-between-onclick-vs-click – miki Sep 27 '17 at 11:14
  • You need to use a [delegated event](http://api.jquery.com/on/#direct-and-delegated-events) – Pete Sep 27 '17 at 11:29
  • you're running the event handler before the element it's targeting exists (because AJAX runs async, so your handler code executes before the ajax has returned). It cannot bind an event to something which isn't there. You have to either use delegated events (look it up here: http://api.jquery.com/on/) or move the "click" handler code into your "success" method, at the end, so that it runs after the element is created in your page. – ADyson Sep 27 '17 at 11:30

3 Answers3

5

Since you add it dynamically, your second input has not an event listener attached to it.

You can solve this by:

$(document).on('click', 'input', function() {});
idontknow
  • 966
  • 8
  • 21
0

Try this

$("body").on("click", "input", function(event){
     alert('bang!!!');
});
Znaneswar
  • 3,329
  • 2
  • 16
  • 24
0

I would solve this using the promise returned by the ajax request:

<body>
   <input type="submit" value="Number 1">
   <script src="jquery.js"></script>
   <script>
       $(document).ready(function(){
               $.ajax('ajax.html').then(function(data) {
                   $('body').append(data);
                   $('input').click(function(){
                       alert('bang!!!');
               });
            });
        });
   </script>
</body>
kevinSpaceyIsKeyserSöze
  • 3,693
  • 2
  • 16
  • 25
  • 1
    why mixing the promise API syntax and the "success" callback syntax? One is sufficient. This is just a bit confusing. Not even sure in which order the two callbacks would be executed (although perhaps the docs make it clear, I haven't looked for that). Easier to just put the handler in the existing "success" rather than define another callback in a different idiom. – ADyson Sep 27 '17 at 11:31
  • @ADyson thanks for your detailed answer! I'll update my answer. – kevinSpaceyIsKeyserSöze Sep 27 '17 at 11:37