3

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

Run
  • 54,938
  • 169
  • 450
  • 748

2 Answers2

3

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();
});
balexandre
  • 73,608
  • 45
  • 233
  • 342
0

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;
});
Atif
  • 10,623
  • 20
  • 63
  • 96
  • how do I trigger it then? I need the alert message inside the `submit`. – Run Jul 13 '13 at 19:22
  • Why don't you set that directly to the form? – Atif Jul 13 '13 at 19:24
  • I have lots of forms on a page, so I want to trigger the closest form from the submit click. does it make sense? thanks. – Run Jul 13 '13 at 19:29
  • Nope, you can still bind an event to form submit and access inner DOM elements of that particular form using `$(this).find()` if you want. – Atif Jul 13 '13 at 19:31