1

I am new to javascript and jquery and I'm trying to submit a form which is validated using the jquery validation plugin using the enter key. This is my code but the form is not being submitted as the alert isn't showing when you press enter. I'm not sure what exactly is happening. I think the page is simply being reloaded when i press enter. There's certainly no validation

<script>
    $(document).ready(function() {

        jQuery.validator.setDefaults({
            errorPlacement: function(error, element) {
                 error.appendTo('#invalid_' + element.attr('id'));

                  }
        });

        var validator = $("#login_form").validate({
            rules: {
                user_email: {
                  required: true,
                  email: true

                },
                password: {
                    required: true
                }
            },
            messages:{
                user_email:{
                    required:"Email required",
                    email: "Must be a valid email"
                },
                password: {
                    required: "Password required"
                }

            }, 


            submitHandler: function(form) {
            alert('submitted');
              $.ajax({
                type: "POST",
                url: "ajax/check_login.php",
                data: $(form).serialize(),
                timeout: 3000,
                success: function(resp) { 
                    if (resp == 'error') {
                        $('#login_error').html('Invalid login');
                    } else {


                        load_user_area();




                    }

                },
                error: function(e) {alert('failed' + e);}
              });
              return false;
            }

        });


$(document).keydown(function(e) { 
    if (e.keyCode == 13) { $('#login_form').submit(); }
});

});

</script>

Thanks in advance for any help!

9
  • does it submit properly when you click the actual form button? May 29, 2013 at 16:55
  • i Suggest you to use keyup instead of 'keydown` May 29, 2013 at 16:58
  • Posting your form's HTML would be helpful. Otherwise, how do we know your selectors are correct?
    – Sparky
    May 29, 2013 at 17:20
  • Please try using e.which instead of e.keycode as this takes care of the browser compatibility issues. or even something like this var keyCode = e.keyCode ? e.keyCode : e.charCode;
    – krishwader
    May 29, 2013 at 17:21
  • 1
    @Mirko What do you mean, function(e)? That's pretty critical to event handling.
    – user229044
    May 29, 2013 at 17:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.