Vlad Holubiev
Vlad Holubiev

Reputation: 5154

How to declare event handler for an element which will be loaded via AJAX?

I have a button which loads using AJAX <input> after click. There is an event handler for it in my JS connected to a page. I tried to declare event handler for <input>'s in the same JS, but they doesn't seem to work.

HTML

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="script2.js"></script>
<button>load</button>

JS

$('button').click(function () {
    $.ajax({
        url: 'additional.html',
        context: document.body,
    }).done(function(html) {
        $('body').append(html);
    })
});
$('input').click(function () {
    alert('aasd');
});

I have made test page, but everything works only after inserting JS to Chrome's Webconsole(due to unknown reasons connected script in <head> doesn't work)

Upvotes: 0

Views: 85

Answers (2)

Chetan hada
Chetan hada

Reputation: 1

use this code:

<script type="text/javascript">
$(document).ready(function(){ 
$('#cl').click(function () {
$.ajax({
    url: 'additional.html',
    context: document.body,
}).done(function(html) {
    $('body').append(html);
})
});
});
$(document).ready(function(){   
$('#cl').click(function () {
alert('aasd');
});
});
</script>

<button id="cl">load</button>

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You should use event delegation .on in your case. Please read here for full reference about .on

Try this,

$(document).on('click','input',function () {
    alert('aasd');
});

Upvotes: 1

Related Questions