cromestant
cromestant

Reputation: 660

JQuery HTML5 form

I have a simple form:

 <div class="container">
        <div class="row">
            <div class="col-md-4 col-md-offset-4" >
                <form class="form-signin" role="form" id="login-form">
                  <h2 class="form-signin-heading">Please sign in</h2>
                  <input type="email" class="form-control" placeholder="Email address" required autofocus>
                  <input type="password" class="form-control" placeholder="Password" required>
                  <label class="checkbox">
                    <input type="checkbox" value="remember-me"> Remember me
                  </label>
                  <button class="btn btn-lg btn-primary btn-block" type="submit" id="login-but-sub">Sign in</button>
                </form>
          </div> <!-- form container -->
</div>
    </div> <!-- /container -->

in an HTML 5 web app, (ember JS if it makes a diff), the HTML 5 form validation as described here works perfectly. I am attaching a JQuery event as such:

$(function(){
    /*Try to restore user once upon loading*/
    restore_user();
    App = Ember.Application.create({ 
                        LOG_TRANSITIONS: true, });

    client = new client()


    App.Router.map(function() {
        this.route('login');
    });

    App.IndexRoute = Ember.Route.extend({
        setupController: function(controller) {
            console.log(client);
            if(!client.isLoggedIn()){
                this.transitionTo('login')
            }
        }
});
    $("#login-but-sub").submit(function(event){
    console.log("login clicked");
});

});

and the issue the event never seems to be fired... If I change it to:

    $("body").submit(function(event){

or

    $("body").on('submit','body',function(event)

then it also works. what is wrong with the first one?

Upvotes: 0

Views: 104

Answers (3)

Felix
Felix

Reputation: 38112

From the docs:

The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to elements. Forms can be submitted either by clicking an explicit , , or , or by pressing Enter when certain form elements have focus.

So, you should use .submit() for <form> elements:

$("#login-form").submit(function(event){
    console.log("login clicked");
});

Seem like your form has been added dynamically, if yes then you need to use event delegation:

$("body").on('submit','#login-form',function(event) {
    console.log("login clicked");
});

Upvotes: 1

anderssonola
anderssonola

Reputation: 2195

The submit event is not fired on the <button> it's fired on the <form>.

in your example the submit event bubbles up to the <body>

Upvotes: 4

andrew
andrew

Reputation: 9593

$('.form-signin').submit() will work.

the submit event belongs to the form, not the submit button

Upvotes: 0

Related Questions