禁用jquery移动表单按钮操作

时间:2012-10-14 16:37:40

标签: jquery jquery-mobile

  

可能重复:
  AJAX Form Submission in 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()
            ;
}

现在,问题在于,每当我点击提交按钮时,我都会被重定向到页面(应该是用户面板),只有一个文字说:

  

未定义

如何禁用jQuery按钮默认执行的操作?

修改 我的事件会触发并显示消息,但我仍然会重定向到表单属性action中定义的网址。

1 个答案:

答案 0 :(得分: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是表单的ID,doShowError()是验证表单输入的函数,如果所有字段都正常则返回true,并且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;
}