2012-06-18 180 views
3

我遇到了一個簡單的html登錄頁面,我做了一個問題,當我提交登錄表單與無效的憑據表單仍然提交,即使我的驗證方法執行「返回false 「命令。我知道這個問題在這裏已經有很多次的問題,但這些問題的答案都沒有幫助我。Onsubmit仍然提交時返回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;」該表單仍然提交。我還檢查了螢火蟲以確保該方法實際上被調用,並確實返回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移動可能是相關的,這是否有可能與我的表單做某事?

+0

將'onSubmit'設置爲'validateForm();返回false;',這在過去對我有效。 – SomeKittens

回答

5

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

爲了防止表單提交從與 Ajax的被自動處理,該data-ajax="false"屬性添加到表格元素。您可以通過ajaxEnabled global config選項完全關閉Ajax表單處理。

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

這是您的格式的demo,但是上面的屬性補充說: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單獨留下特定的表單,以便我們可以自行提交。

+0

看來,這正是我想念的,謝謝一堆! – Alejo

+1

儘管他刪除了他的答案,但還是要感謝Rob W指定爲什麼使用.val()而不是.attr() – Alejo

0

在validateForm()函數,你已經使用了兩個不確定變量(userLblpassLbl)。 爲變量和檢查定義值。

相關問題