jquery在表单中返回false

时间:2010-04-07 18:19:15

标签: javascript jquery

<script LANGUAGE="JavaScript">
function confirmSubmit() {
    jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) {
        if(r) {
            return true;
        } else {
            return false;
        }
    });
}
</script>

<form name='cancel_form'id='cancel_form' method='POST' action="">
<center>
<input type='submit' name='confirm_appointment' value='Cancel Appointment' onclick='return confirmSubmit();'>
</center>
</form>

<script type='text/javascript'>
var ajax_load = "<img class='loading' src='img/load.gif' alt='loading...' />";
var saveUrl = "<?php echo $this->url(array('controller' => 'appointment', 'action' =>'cancelsave'));?>";
$('#cancel_form').ajaxForm({ success: saveCallbk , url : saveUrl });
function saveCallbk(responseText) {
    jAlert(responseText,'Alert Dialog');
    if(responseText.indexOf("ERROR")<0) {
        $(location).attr('href',redirectUrl);
    }
}
</script>

当我提交表单时,我调用此函数并使用jQuery中的jConfirm。我打印r。它正确打印(例如truefalse),但return falsereturn true无效 - 它只显示弹出窗口并提交表单,并且不会等待确认。怎么解决这个问题?

ajaxForm插件自己负责提交,需要一个提交按钮。如果我使用:

function confirmSubmit() {
    var agree=confirm("Is the Appointment Cancelled?");
    if (agree) {
        return true;
    } else {
        return false;
    }
}

就像默认的javascript一样,效果很好

3 个答案:

答案 0 :(得分:3)

使用type =“button”而不是type =“submit”并将其附加到表单按钮的click事件上。

$('#button').click(function () {
    jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) {
        if (r) {
            $('#form').submit();
        }
    });

});

答案 1 :(得分:1)

Ivo说的话。

您的函数confirmSubmit应该返回true或false。

编辑 -

我不熟悉jConfirm,但你可能需要从jConfirm返回结果,就像这样。

<script>
function confirmSubmit() 
{ 
    return jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog',         
        function(r) {      
            if(r){return true;} else {return false;} 
        });
}
</script>

如果是这种情况,你可以完全取消confirmSubmit(),然后说:

$('#form').submit(function() {
   return jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) { return r; } );
});

希望这会有所帮助......

Dang认为Ivo很好:-)就个人而言,我做了Ivo所展示的。创建type="button"的输入,然后委派点击功能。

答案 2 :(得分:1)

这是我使用JavaScript和jQuery取消提交事件的方法:

首先,我有一个名为cancelEvent的实用程序功能:(我从this blog entry获取的。)

function cancelEvent(e)
{
    e = e ? e : window.event;
    if(e.stopPropagation)
            e.stopPropagation();
    if(e.preventDefault)
            e.preventDefault();
    e.cancelBubble = true;
    e.cancel = true;
    e.returnValue = false;
    return false;
}

然后我将拥有包含如下代码的主JavaScript文件:

function validateForm(e)
{
    var validated = true;
    /*
    Validation code goes here.
    If validation fails set validated to false
    */
    //If validation fails then at the end I'll want to cancel the submit event
    if(validated)
    {
        return true;
    }
    return cancelEvent(e);
}

jQuery(document).ready(function()
{
    jQuery("#theForm").submit(validateForm);
}