Roland
Roland

Reputation: 9691

Assign click event after an element was created dynamically

So, instead of having a form in the HTML, I decided to create the form on fly and append it to another element (in my case a <section>, but that will be an option in the near future).

I'm using this method:

var formWrapper = ['<div class="content-login">','</div>'];

var form = [
    '<form name="login-form" class="login-form" method="post" action="#">',
        '<fieldset class="login-fields">',
            '<fieldset class="username-wrapper">',
                '<label for="username" class="user-img"><img src="assets/gfx/user.png" alt="Username" /></label>',
                '<input type="text" name="username" class="username" placeholder="Username" value="" autocomplete="off" />',
            '</fieldset>',
            '<fieldset class="password-wrapper">',
                '<label for="password" class="pass-img"><img src="assets/gfx/password.png" alt="Password" /></label>',
                '<input type="password" name="password" class="password" placeholder="Password" value="" autocomplete="off" />',
            '</fieldset>',
            '<fieldset class="login-wrapper">',
                '<button type="submit" name="login" class="login">Login</button>',
            '</fieldset>',
        '</fieldset>',
    '</form>'       
];

setTimeout(function () {
    $(formWrapper.join('')).appendTo('section').hide();
    $(form.join('')).appendTo('.content-login');
    $('.content-login').fadeIn('slow');
}, 1500);

This way I have a nice fade in effect and it will give me the opportunity to change whatever I want after I fully develop it.

But my question is in fact the following: I have a form, so of course I will use Ajax to submit it, and I already have the script for that. The thing is now, when I click on the button, the .click event does not occur, it only takes me to the default action of the form which is "#" in my case. Why is that ?

Here is the other part of the script, for a better understanding :

$('.login-form .login').click(function(){
    if($('input.username').val() == "" || $('input.password').val() == "")
    {
        console.log('Please enter Username & Password');
        $('.login-form').effect("shake", { distance: 40, times: 2 }, 100);
        return false;
    }
    else {  

        $('.login-fields').fadeOut();
        $('.login-form').spin("login", "#ffffff");      
        $.ajax
        ({
            type: 'POST',
            url: 'assets/class/login/process.php',
            dataType: 'json',
            data:
            {
                username: $('input.username').val(),
                password: $('input.password').val()
            },
            success:function(data)
            {
                if(!(data.lockdown == true)) {
                    if(data.error === true) {   
                        console.log(data.message);
                        $('.login-form').spin(false);
                        $('.login-fields').fadeIn();
                        $('.login-form').effect("shake", { distance: 40, times: 2 }, 100);
                    }
                        else {
                            console.log(data.message);
                            $('.login-form').spin(false);
                            $('.login-fields').fadeIn();
                            $('.content-login').fadeOut();

                            var structure = [
                                '<div class="after-login">',
                                    '<div class="inside">',
                                        '<div class="row-one">',
                                            '<h1>',data.message,'</h1>',
                                        '</div>',
                                        '<div class="row-two">',
                                            '<a class="cancel" href="',links.cancel,'?logout">Cancel</a>',
                                            '<a class="continue" href="',links.proceed,'">Continue</a>',
                                        '</div>',
                                    '</div>',
                                '</div>'
                            ];

                            setTimeout(function () {
                                $(structure.join('')).appendTo('section').fadeIn('slow');
                            }, 1500);

                        }
                }
                    else {
                        console.log(data.message);
                        $('.login-form').spin(false);
                        $('.content-login').fadeOut();

                        var structure = [
                            '<div class="system-lockdown">',
                                '<div class="inside">',
                                    '<div class="row-one">',
                                        '<h1>',data.message,'</h1>',
                                    '</div>',
                                    '<div class="row-two">',
                                        '<a class="back" href="',links.goback,'">Back</a>',
                                    '</div>',
                                '</div>',
                            '</div>'
                        ];

                        setTimeout(function () {
                            $(structure.join('')).appendTo('section').fadeIn('slow');
                        }, 1500);
                    }
            },
            error:function(XMLHttpRequest,textStatus,errorThrown)
            {
                console.log('A PHP error triggered this, check your PHP log file for more information');
            }
        });
        return false;
    }
});

Upvotes: 0

Views: 373

Answers (2)

Adam Rackis
Adam Rackis

Reputation: 83358

The preferred way to handle events with dynamically added content is with on()—or delegate, since you're on jQuery 1.6

$(document).delegate('.login-form .login', 'click', function(){
});

Note that this will listen to every single click anywhere in your document. Ideally you'd like to identify some more narrow container from which all clicks will come, and listen to that. So if all these clicks will be coming from your section, you'd do this

$("section").delegate('.login-form .login', 'click', function(){
});

Upvotes: 1

Bojangles
Bojangles

Reputation: 101473

$.click() will only work on elements that have been created before the handler was created.

Instead, use $.live() instead:

$('.login-form .login').live('click', function() {
    // Your code
});

If you're using jQuery 1.7 or above, you can also use $.on() in a similar way:

$('.login-form .login').on('click', function() {
    // Your code
});

Upvotes: 2

Related Questions