0

I created a div as defined below

       <div class="area1">
        </div>

With this ajax call I changed the html for above div

$('#abutton').click(function(e) {
    e.preventDefault();
    $.ajax({
        url: 'do',
        type: 'POST',
        dataType: 'json',
        cache: false,
        data: {id:this.id},
        success: function(data) {
            $('.area1').html(data);
        },
        failure: function() {
            alert('Please try again..!');
        }
    });
});

now div content looks like this

       <div class="area1">
            <input type="text" placeholder='Name'>
            <button id='submit'>Submit</button>
        </div>

Now I want to perform some action on button click

$('.area1 button').click(function(e){
    e.preventDefault();
    alert(this.id) ;
});

but this second ajax is not selecting the button

Can anyone tell the correct method

Raman
  • 25
  • 3

1 Answers1

0
$(document).on("click","div.area1 button",function(e) {
  e.preventDefault();
  alert(this.id) ;
});

you can try this

if your page was dynamically creating elements dosomething you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document.

Avni
  • 106
  • 5
  • 3
    While this is correct, it will always be a good idea to leave a comment about why this fixes the problem, so the OP or others will learn about what the problem was – Carsten Løvbo Andersen Mar 31 '22 at 06:09