2012-10-14 33 views
0

可能重複:
AJAX Form Submission in jQuery Mobile禁用jQuery Mobile的形式按鈕動作

我有一個表格,我使用jQuery檢查和驗證的形式,因此,如果表格是空的,它不會提交表格,只會提醒「請填寫所有字段」。

function doShowError(eForm, sField, iInd, sError) { 
    var $Field = $("[name='" + sField + "']", eForm); // single (system) field 
    if(!$Field.length) // couple field 
     $Field = $("[name='" + sField + '[' + iInd + ']' + "']", eForm); 
    if(!$Field.length) // couple multi-select 
     $Field = $("[name='" + sField + '[' + iInd + '][]' + "']", eForm); 
    if(!$Field.length) // couple range (two fields) 
     $Field = $("[name='" + sField + '[' + iInd + '][0]' + "'],[name='" + sField + '[' + iInd + '][1]' + "']", eForm); 

    //alert(sField + ' ' + $Field.length); 

    $Field.parents('div:first').addClass('error'); 

    $Field 
    .parents('div:first') 
     .addClass('error') 
     .children('img.warn') 
      .attr('float_info', sError) 
      //.show() 
      ; 
} 

現在,問題是,每當我提交按鈕點擊,我得到只是一個短信說重定向到頁面(這應該是用戶面板):

undefined

如何禁用jQuery按鈕的默認功能?

編輯: 我的事件觸發和消息顯示,但我仍然重定向到在窗體的屬性action定義的URL。

+0

嗨!你在哪裏調用你的函數'doShowError'?你能提供更多的代碼嗎? – Littm

回答

0

在驗證表單字段(應在submit事件中調用)的函數中,如果驗證成功,則需要返回true,否則返回false

通過這種方式,您可以防止表單在驗證失敗時導航到action屬性中定義的URL。

你可以嘗試這樣的事:在相反

$(function() { 
    $("#your_form").submit(function() { 
     // Define `sField` 
     var sField = // SOMETHING 

     // Define `iInd` 
     var iInd = // SOMETHING 

     // Define `sError` 
     var sError = // SOMETHING 

     return doShowError($(this), sField, iInd, sError); 
    }); 
}); 

其中#your_form是您的形式和doShowError()的ID是驗證表單的輸入功能,返回true如果所有的字段都ok了,else案件。

在這種情況下,您可能需要修改功能doShowError,以便它將返回truefalse,如上所述。你可以改變它是這樣的:

function doShowError(eForm, sField, iInd, sError) { 

    // `haserror`: boolean output which will equal `true` 
    // if all the fields are correct, and `else` otherwise 
    var haserror = true; 

    var $Field = $("[name='" + sField + "']", eForm); // single (system) field 
    if(!$Field.length) { // couple field 
     $Field = $("[name='" + sField + '[' + iInd + ']' + "']", eForm); 
     haserror = false; 
    } 
    if(!$Field.length) { // couple multi-select 
     $Field = $("[name='" + sField + '[' + iInd + '][]' + "']", eForm); 
     haserror = false; 
    } 
    if(!$Field.length) { // couple range (two fields) 
     $Field = $("[name='" + sField + '[' + iInd + '][0]' + "'],[name='" + sField + '[' + iInd + '][1]' + "']", eForm); 
     haserror = false; 
    } 

    //alert(sField + ' ' + $Field.length); 

    $Field.parents('div:first').addClass('error'); 

    $Field.parents('div:first') 
     .addClass('error') 
     .children('img.warn') 
      .attr('float_info', sError) 
      //.show() 
      ; 

    return haserror; 
} 
+0

感謝您的回覆,但仍然面臨同樣的問題。 我的代碼應該做的事情是停留在同一頁面上,只是提醒錯誤,但現在我到達操作頁面,不僅僅是它,而且它只有'undefined ' –