Onsubmit still submits when returning false

后端 未结 2 1553
无人及你
无人及你 2020-12-21 06:08

I\'m having a problem with a simple html login page I made, where when I submit the login form with invalid credentials the form still submits, even though my validation met

相关标签:
2条回答
  • 2020-12-21 06:29

    In validateForm() function, you've used two undefined variables(userLbl and passLbl). Define value for the variables and check.

    0 讨论(0)
  • 2020-12-21 06:38

    If you want to handle form submission on your own, you will need to add the data-ajax="false" attribute to the <form> tag so jQuery Mobile leaves it alone.

    To prevent form submissions from being automatically handled with Ajax, add the data-ajax="false" attribute to the form element. You can also turn off Ajax form handling completely via the ajaxEnabled global config option.

    Source: http://jquerymobile.com/demos/1.1.0/docs/forms/forms-sample.html

    Here is a demo of your form but with the above attribute added: http://jsfiddle.net/XtMw9/

    Doing this means that you will have to manually submit your form:

    function validateForm()
    {
        var usernameTxt = $("#userField").val();
        var passwordTxt = $("#passField").val();//notice the use of .val() instead of .attr()
    
        if (usernameTxt == "" || passwordTxt == "" || (usernameTxt == userLbl && passwordTxt == passLbl))
        {
            $("#errorMsg").html("Please enter a username and password.");
            return false;
        }
    
        var $form = $('form');
        $.ajax({
            url     : $form.attr('action'),
            type    : $form.attr('method'),
            data    : $form.serialize(),
            success : function (response) { ... },
            error   : function (a, b, c) { console.log(b); }
        });
    }
    

    Explanation

    This works because by default jQuery Mobile will attempt to submit any form via AJAX. Using the data-ajax="false" attribute we can tell jQuery Mobile to leave a specific form alone so we can submit it on our own.

    0 讨论(0)
提交回复
热议问题