1

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;
    }
});
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
Kate Wintz
  • 633
  • 2
  • 11
  • 24
  • I am sorry, but I didn't get what exactly is not working. On Submitting request there's a submit error. Is that what you are referring to? – Sid Nov 20 '11 at 15:58

1 Answers1

3

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 2
    If you are using jQuery 1.7 you should use `.on()` if you use jQuery < 1.7 you should use `.delegate()`. Don't use `.live()` since it is way slower than the others. – PeeHaa Nov 20 '11 at 16:03
  • Yes that's true - I haven't up'd to 1.7 yet so I didn't know the ".on()" syntax exactly :-) – Pointy Nov 20 '11 at 16:07
  • I HAD to upgrade to 1.7 since WebKit is trowing errors like hell otherwise. http://stackoverflow.com/questions/7825448/webkit-issues-with-event-layerx-and-event-layery :D – PeeHaa Nov 20 '11 at 16:09
  • Ok, i have other function and add it in code and don't work my code, please see my demo here: http://jsfiddle.net/Jvw6N/4/ – Kate Wintz Nov 20 '11 at 16:59
  • There is no function called "autocomplet_valid". You should be using a debugging tool, because it would have told you exactly that. – Pointy Nov 20 '11 at 17:02