【问题标题】:How do I stop form from automatically submitting? (Django/jQuery)如何阻止表单自动提交? (Django/jQuery)
【发布时间】:2014-01-26 18:03:56
【问题描述】:

我有一个问题,即使我没有告诉它提交表单(在 Javascript 中)。我有一个表单按钮的事件处理程序,它检查输入是否是大于 0 的有效整数,并对其进行处理。问题是即使它发现这是错误的,表单仍然会提交。

这是我的表单代码:

<form id="case_form" method="post" action="/dms/create/">
    {% csrf_token %}
    <h3>Case ID</h3>
    <input name="caseID" id="caseNum" type="text" class="form-control" placeholder="ID of Case to create" required
           autofocus><br/>
    <button class="btn btn-lg btn-primary btn-block" id="submitButton">Create Case</button>
</form>

还有我的 Javascript 事件处理程序。

$('#submitButton').click(function () {
    numVal = $("#caseNum").val();
    if (Math.floor(numVal) == numVal && $.isNumeric(numVal) && numVal > 0){
        $("#case_form").submit();
    }else{
        $("#errorDisplay").show();
        //Code gets here but still submits once leaving function
    }
});

【问题讨论】:

    标签: javascript jquery html django forms


    【解决方案1】:

    这是我的第一个答案:D

    试试这个。

    <form onsubmit="return fnValidate()" ...> ... </form>
    

    Javascript:

    function fnValidate(){ 
        var numVal = $("#caseNum").val();
        if (Math.floor(numVal) == numVal && $.isNumeric(numVal) && numVal > 0){
            return true;
        }else{
           $("#errorDisplay").show();
           return false;
        }
    }
    

    当 fnValidate 返回 True 时,您的表单将被提交。当函数返回 false 时,不会提交。

    祝你好运!

    【讨论】:

    • 哦,很酷,但我很好奇你为什么要return 而不是仅仅调用函数? :)
    • 您好,当从 fnValidate 返回时,如果值为 True,则将提交表单。另一方面,当它返回 False 时,不会提交任何内容。
    【解决方案2】:

    解决了...

    很抱歉提交了这个问题,我试图弄清楚很久,然后是 Sod 定律 - 一旦我提交问题,我就会有一个“哦,这太明显了”的时刻。

    我忘记放了...

    type=button

    ...在按钮 HTML 中。

    【讨论】:

      【解决方案3】:

      这发生在我身上,我意识到我必须将我的注释代码放在这些 Django 注释标签中才能停止触发:{% comment %} cmets here {% endcomment %}。

      【讨论】:

      • 这是作为答案发布的,但不会尝试回答问题。
      猜你喜欢
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-02
      • 2018-01-05
      • 1970-01-01
      相关资源
      最近更新 更多