0

I am loading an element through jQuery AJAX whose id is questionBeanPV.coAppQuestions150.answerText I know the id is too long and it contains jQuery's '.' but i cannot change the id.

I want a funnction to be called when this element is clicked. However the following code is not working.

$(document).ready(function(){       
    $('#questionBeanPV\\.coAppQuestions150\\.answerText').click(function(){
        alert('Hello !');
    });
});

I have observed that this doesnt work for any dynamically loaded element. What am i missing ? Is this the correct way or some other way is there?

Abhishek Singh
  • 9,749
  • 20
  • 71
  • 102
  • The event listener should be attached to the document, so any new elements that created after attaching the listener can be considered to fire the event. – MaveRick Mar 10 '14 at 14:39

3 Answers3

4

You can use event delegation here:

$('body').on('click', '#questionBeanPV\\.coAppQuestions150\\.answerText', function() {
    alert('Hello !');
});

This technique will helps you to attach any event to dynamically created elements.

Felix
  • 37,443
  • 7
  • 40
  • 55
  • Maybe you'd post another question with relevant code. We'll try to help you :-) – Felix Mar 10 '14 at 15:51
  • here ---> http://stackoverflow.com/questions/22303650/jquery-autocomplete-not-working-on-dynamically-loaded-elements? – Abhishek Singh Mar 11 '14 at 05:39
  • This might help: http://stackoverflow.com/questions/2663573/jquery-autocomplete-for-dynamically-created-inputs – Felix Mar 11 '14 at 05:43
1

you should use delegate for that

$(document).on("click","#questionBeanPV\\.coAppQuestions150\\.answerText",function(){
   //some operation
});

It helps you to attach handlers for the future elements

Anoop Joshi P
  • 24,863
  • 8
  • 29
  • 52
0

Use event delegation:

$(document).on("click", "#questionBeanPV\\.coAppQuestions150\\.answerText", function() {
tymeJV
  • 102,126
  • 13
  • 159
  • 155