Search code examples
javascriptjqueryajaxjquery-eventscolorbox

Why is click event handler for a submit button in a colorbox defined in a jQuery prototype method not invoked


I have added a function to jQuery prototype as below. What I want to do is when this method is invoked, generate an html form based on the arguments passed to the method and show it in a colorbox.

(function($) {

$.fn.myFunction = function(data){
    
    var form = $('<form name="people"></form>');
    
    var index;
    for (index = 0; index < data.length; index++) {
          
        var match = data[index];
        $('<input type="radio" name="person">' + match['name'] + ' [' + match['uri'] + ']<br> ')
        .attr("value", match['uri'])
        .appendTo(form);
    }

    $('<input type="button" id="a_button" value="Add"/><br>')
    .appendTo(form);
    
    var list = $('<div>').append(form).html();

    $('#a_button').click(
            
            function(){
                console.log('message from event handler');
            }
    );
    
    $.colorbox({ innerWidth:420, innerHeight:315, html: list });
};

})(jQuery);

As you can see, form has a button called Add using which I hope to make an ajax request. But unfortunately click event handler attached to this button doesn't seem to be invoked.

Does anyone have any idea about what's wrong here? myFunction is actually invoked by a drupal ajax command in case if that's helpful.


Solution

  • You are appending the form to the DOM after attaching the event handler.

    $('#a_button') searches the DOM at that specific point in time, but the form is not added to the DOM until after your call to colorbox with list as a parameter.

    Try a permanent delegated event handler instead (or simply add the click handler after the colorbox line).

    e.g.

    $(document).on("click", "#a_button", function(){ 
        console.log('message from event handler');
    }); 
    

    or

    $.colorbox({ innerWidth:420, innerHeight:315, html: list });
    $('#a_button').click(
    
            function(){
                console.log('message from event handler');
            }
    );