Shawn McBride
Shawn McBride

Reputation: 552

Jquery submit not working when I add a handler.

I've got a bunch of checkboxes on a page and I want to auto-submit anytime one of them is modified, and capture the response. If I run this code I can see the first console message, but not the second. It seems like the form is never submitted.

<script type ="text/javascript" >
    $(document).ready(function(){
            $('.project_checkbox').change(function(){
                console.log('this does get called');
                $(this).parent().submit(function() {
                    console.log('this never gets called');
                    return false;
                });
            });
    });
</script>

If I remove the handler and run this instead the form submits and my browser opens up the URL of the appropriate form. I can tell from the output that it's reading the correct vale for the checkbox:

<script type ="text/javascript" >
    $(document).ready(function(){
            $('.project_checkbox').change(function(){
                console.log('this does get called');
                $(this).parent().submit();
            });
    });
</script>

Can anyone tell why adding the handler in this case would kill the submission?

Upvotes: 1

Views: 914

Answers (2)

Matt Bradley
Matt Bradley

Reputation: 4495

.submit( function() { } ) is different from .submit(). The first one sets the function that gets called when the form is submitted, equivalent to .bind('submit', function() { } ). The second one actually triggers the submit event, equivalent to .trigger('submit'). See http://api.jquery.com/submit/ for more info.

Upvotes: 1

user834912
user834912

Reputation:

You're binding an event to $(this).parent(), so it will only be executed when the form is submitted. To submit the form, just call the method directly after the binding: $(this).parent().submit.

Upvotes: 1

Related Questions