Kate Wintz
Kate Wintz

Reputation: 643

Validation doesn't work after adding an input with jQuery

After clicking on Add Input and adding an input, clicking on the added button doesn't call the required_valid() function in $('.submit').submit(function () {.... Why is this?

DEMO: http://jsfiddle.net/Jvw6N/

<a href="" class="add_input">Add Input</a>
<div class="get_input"></div>



$('.add_input').live('click', function(e){
    e.preventDefault();
    $('.get_input').append('<form class="submit"><input name="test" class="required"> <br /> <button>Click Me</button></form>')
})
function required_valid() {
    var result = true;
    $('.required').each(function () {
        if (!$(this).val()) {
            $(this).css("background", "#ffc4c4");
            result = false;
        }
        $(this).keyup(function () {
            $(this).css("background", "#FFFFEC");
        })
    });
    return result;
}

$('.submit').submit(function () {
    var passed = true;
    //passed = required_selectbox() && passed;
    passed = required_valid() && passed;
    if (!passed) {
        $('#loadingDiv, #overlay').hide();
        return false;
    }
});

Upvotes: 1

Views: 216

Answers (1)

Pointy
Pointy

Reputation: 413767

You need to set up your "submit" handlers with ".live()" (or ".delegate()" or the new ".on()") just like your "addInput" button:

$('body').delegate('.submit', 'submit', function() {
  // your submit code here
});

You're adding those forms dynamically, so your handler isn't actually bound to any of them.

Alternatively, you could bind the handler when you add the form.

Upvotes: 3

Related Questions