Bruno Lamps
Bruno Lamps

Reputation: 646

Can't call javascript from ajax div

I have some content loaded in my page using ajax. I want to run a JS function when some anchors are clicked. These anchors belongs to the code loaded using ajax. Both the ajax request and the JS function are located in a separate JS file, inside a jQuery(document).ready(function() {.

I have a few dozens functions in this JS file, and they're running fine, but this specific function is the only one called by code retrieved using ajax, and it is not working. My code:

html main file:

<!-- code -->
<div id="ajaxContentGoesHere">
<!-- content inserted here by ajax function -->
<td><a href="#" id="aLancamentoEdit<?php echo $lancamento['Lancamento']['lan_itid']; ?>">Editar</a></td>
</div>    
<script src="/js/myJS.js"></script>
</body> 

/js/myJS.js file:

jQuery(document).ready(function() {
/*some other functions here*/
 $("[id^='aLancamentoEdit']").click(function(){
        console.log(1);
}
});

I tried to put the $("[id^='aLancamentoEdit']").click(function(){ inside the html main file, in a tag after the /js/myJS.js call. Didn't work. Also tried to change the selector to match my anchor class (I declared a class for this). No success either. Finally tried also to put a name in the function and call it on onclick="" inside the anchor. Failed again.

What am I doing wrong?

Upvotes: 0

Views: 154

Answers (2)

Rajesh
Rajesh

Reputation: 3778

Since the element by id starting with 'aLancamentoEdit' is dynamically added by ajax, you need to bind click handler to parent:

$('#ajaxContentGoesHere').on('click', "[id^='aLancamentoEdit']", function() {
   console.log(1);
});

Upvotes: 4

Kiran
Kiran

Reputation: 20313

Use .on() for dynamic element events (ajax content in your case). Try:

jQuery(document).ready(function() {
/*some other functions here*/
 $("#ajaxContentGoesHere").on("click","[id^='aLancamentoEdit']",function(){
        console.log(1);
}
});

Upvotes: 3

Related Questions