user756659
user756659

Reputation: 3512

attach jquery handler to modal after it has been loaded

I am loading a modal on click of #show-delete. Inside that modal (which is a remote page) I want to attach a handler for on click of #delete-user. This handler is not working at all and the button does nothing.

If I place the deleteAccount function inside the actual modal page (m_delete_user.php) the handler works, but for sake of ease and other operations I would like to keep these in index.php.

inside index.php :

// show delete user modal
var showDelete = function() {
    $('#show-delete').on('click', function () {
        var $form = $(this).closest('form');
        var username = $form.find("select[name=account_username]").val();

        //open the modal with the username value
        $('#modal-ajax').load('/spc_admin/modals/m_delete_user.php?username='+username);
        $('#modal-ajax').modal('show');

        // initialize the button handler
        deleteAccount();                
    });
}

// delete user (modal delete button)
var deleteAccount = function() {
    $('#delete-user').on('click', function () {
        var $form = $(this).closest('form');
        $.ajax({
            type: 'post',
            url: '/spc_admin/process/p_delete_user.php',
            data: $form.serialize(),
            dataType : 'json'
        }).done(function (response) {
            if (response.success) {

... and continued

Upvotes: 0

Views: 56

Answers (1)

jfriend00
jfriend00

Reputation: 707158

You have to wait until the .load() operation is complete because it's asynchronous. You can do that using the completion function passed to .load() and trigger the installation of your deleteAccount handlers with the completion function.

// delete user (modal delete button)
var deleteAccount = function() {
    $('#delete-user').on('click', function () {
        var $form = $(this).closest('form');
        $.ajax({
            type: 'post',
            url: '/spc_admin/process/p_delete_user.php',
            data: $form.serialize(),
            dataType : 'json'
        }).done(function (response) {
            if (response.success) {

... and continued

// show delete user modal
var showDelete = function() {
    $('#show-delete').on('click', function () {
        var $form = $(this).closest('form');
        var username = $form.find("select[name=account_username]").val();

        //open the modal with the username value
        // ==> deleteAccount added as a completion function here
        $('#modal-ajax').load('/spc_admin/modals/m_delete_user.php?username='+username, deleteAccount);
        $('#modal-ajax').modal('show');

    });
}

Upvotes: 1

Related Questions