0

I have an onClick event on a button that is created using data returned from the server (via Ajax). The outline of my code is this:

$(document).on('pageinit', function() {
$.ajax({
    url: '/',
    dataType: 'json', 
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    data: textInput,
    success: function (response) {
        if(response.error_code!=null){
            alert(response.user_message);
        }
        else {
         //code to generate button with id tag `cvResults`

         $('#cvResults').click(function(e) {
         // some code here, redirects to another mobile page
        }
        },//then remainder of ajax function

I initially tried putting the onClick function outside the Ajax call (but within the pageinit). This wouldn't trigger because the page would initiate without any #cvResults tags and hence not load the function.

I now have a different problem. When you click this button and go to the other page, if you then press back and try to click the button again, the event isn't triggered. This makes sense because there has been no response from Ajax.

How do I cater for both of these scenarios, and just permanently have the onClick event listening when the #cvResults tag is present?

MDalt
  • 1,681
  • 2
  • 24
  • 46

1 Answers1

1

Try this method to bind any click events for dynamically created elements.

$('document').on('click','#cvResults',function(){
    // your code.
})

Since your page init without this element the event will not bind if you do it in the regular way.

Imesh Chandrasiri
  • 5,558
  • 15
  • 60
  • 103
  • This is not correct. The delegation syntax is `$(document).on('click', '#cvResults', function...);` – Barmar Mar 12 '15 at 08:27
  • Changed the syntax.! – Imesh Chandrasiri Mar 12 '15 at 08:28
  • Thanks guys. Where do I put this function? I have just tried it 1) outside of the existing onInit 2) within the Ajax Success Call 3) within the document onInit but outside of the Ajax function. Neither triggered the function upon clicking the function. – MDalt Mar 12 '15 at 18:41