Question

Why can't I trigger the submit button's closest form in this example below?

html,

<form name="input" action="html_form_action.asp" method="get">
Username: <input type="text" name="user">
<input type="submit" value="Submit">
</form>

jquery,

$('input[type=submit]').click(function(){

    $(this).closest('form').unbind('submit').submit(function(){
           alert("hello world");
        return false;
    });
    return false;
});

I should get the alert message, but I can't. What have I done wrong?

the jsfiddle

Was it helpful?

Solution

wow, that's a lot of bubbling events...

you keep returning false and binding and unbiding the event... that will not work, but you can simple change your submit button to a normal button, for example:

<form name="input" action="html_form_action.asp" method="get">
    Username: <input type="text" name="user" />
    <input type="button" value="Submit" class="btn-submit" />
</form>

and write

$(".btn-submit").click(function() {
    $(this).prop("disabled", true); // dont allow more clicks 
    alert('about to submit...');
    $(this).closest("form").submit();
    alert('done!');
});

DEMO in JsBin: http://jsbin.com/elokov/1/


with an ajax call to submit the form

$(".btn-submit").click(function(evt) {
    $(this).prop("disabled", true); // dont allow more clicks 
    alert('about to submit...');

    var frm = $(this).closest("form"); // our form

    $.ajax(
        type: frm.attr("method"),
        url:  frm.attr("action"),
        data: frm.serialize(),
        success: function(data) {
            alert('all went well');
        },
        success: function(jqXHR, textStatus) {
            alert('err, something messed up! ' + textStatus);
        }
    );

    return false; // or use evt.preventDefault();
});

OTHER TIPS

Because your code is simply binding the submit event however it is not triggering the submit event. If you just want to prevent form from submission and alter then this should be enough

$('input[type=submit]').click(function (e) {
    alert("hello world");
    return false;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top