簡體   English   中英

返回false時,Onsubmit仍然提交

[英]Onsubmit still submits when returning false

我遇到了一個簡單的html登錄頁面的問題,當我提交帶有無效憑據的登錄表單時,表單仍然提交,即使我的驗證方法正在執行“return false”命令。 我知道這個問題在這里被多次提出過,但這些問題的答案都沒有幫助我。

我的html表格如下:

<form onSubmit="return validateForm();" method="get" action="TestPage.html">
    <div id="centralPoint" class="frame">
        <select id="centralPointSelect" data-inline="true" data-mini="true" data-native-menu="false" name="centralPoint"></select>
    </div>
    <div id="credentialsFrame" class="frame">
        <input id="userField" type="text" name="Username" />
        <input id="passField" type="password" name="Password" />
    </div>
    <div id="errorMsg"></div>
    <input id="loginBtn" type="submit" value="Login" />
    <div id="rememberMe" class="frame">
        <input type="checkbox" id="checkbox-1" class="custom" data-mini="true" name="rememberMe" />
        <label for="checkbox-1">Keep me signed in</label>
    </div>
    <div id="forgotPassFrame">
        <input id="forgotPass" type="button" data-mini="true" value="Forgot password?" />
    </div>
</form>

這是我的javascript方法。 請注意,即使這里唯一的代碼行是“return false;” 表格仍然提交。 我還檢查了firebug,以確保該方法實際上被調用,並且它確實返回false,並且全部檢出。

function validateForm()
{
    var usernameTxt = $("#userField").attr("value");
    var passwordTxt = $("#passField").attr("value");

    if (usernameTxt == "" || passwordTxt == "" || (usernameTxt == userLbl && passwordTxt == passLbl))
    {
        $("#errorMsg").html("Please enter a username and password.");
        return false;
    }
}

有什么東西真的很明顯我錯過了嗎? 我沒有以任何方式綁定onsubmit事件,除了你在html表單標簽中看到的內容,我也沒有為提交按鈕分配任何點擊處理程序。

我正在使用JQuery mobile可能是相關的,這是否可能與我的表單有關?

如果您想自己處理表單提交,則需要將data-ajax="false"屬性添加到<form>標記中,以便jQuery Mobile單獨使用它。

要防止使用Ajax自動處理表單提交,請將data-ajax="false"屬性添加到表單元素。 您還可以通過ajaxEnabled全局配置選項完全關閉Ajax表單處理。

資料來源: http//jquerymobile.com/demos/1.1.0/docs/forms/forms-sample.html

以下是您的表單的演示,但添加了以上屬性: http//jsfiddle.net/XtMw9/

這樣做意味着您必須手動提交表單:

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); }
    });
}

說明

這是有效的,因為默認情況下jQuery Mobile將嘗試通過AJAX提交任何表單。 使用data-ajax="false"屬性,我們可以告訴jQuery Mobile單獨留下一個特定的表單,以便我們可以自己提交。

在validateForm()函數中,您使用了兩個未定義的變量( userLblpassLbl )。 定義變量的值並檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM