簡體   English   中英

JavaScript 停止表單提交的代碼

[英]JavaScript code to stop form submission

停止提交表單的一種方法是從您的 JavaScript function 返回 false。

單擊提交按鈕時,將調用驗證 function。 我有一個表單驗證案例。 如果滿足該條件,我將調用名為returnToPreviousPage() 的 function;

function returnToPreviousPage() {
    window.history.back();
}

我正在使用 JavaScript 和Dojo 工具包

它不是返回到上一頁,而是提交表單。 我怎樣才能中止這次提交並返回到上一頁?

可以使用函數的返回值來阻止表單提交

<form name="myForm" onsubmit="return validateMyForm();"> 

和功能一樣

<script type="text/javascript">
function validateMyForm()
{
  if(check if your conditions are not satisfying)
  { 
    alert("validation failed false");
    returnToPreviousPage();
    return false;
  }

  alert("validations passed");
  return true;
}
</script>

對於 Chrome 27.0.1453.116 m 如果上述代碼不起作用,請將事件處理程序的參數的 returnValue字段設置為 false 以使其工作。

感謝山姆分享信息。

編輯 :

感謝 Vikram 為 validateMyForm() 返回 false 的解決方法:

 <form onsubmit="event.preventDefault(); validateMyForm();">

其中 validateMyForm() 是一個在驗證失敗時返回 false 的函數。 關鍵是使用name事件。 我們不能用於 egepreventDefault()

使用阻止默認值

道場工具包

dojo.connect(form, "onsubmit", function(evt) {
    evt.preventDefault();
    window.history.back();
});

jQuery

$('#form').submit(function (evt) {
    evt.preventDefault();
    window.history.back();
});

香草 JavaScript

if (element.addEventListener) {
    element.addEventListener("submit", function(evt) {
        evt.preventDefault();
        window.history.back();
    }, true);
}
else {
    element.attachEvent('onsubmit', function(evt){
        evt.preventDefault();
        window.history.back();
    });
}

截至目前,以下工作(在 Chrome 和 Firefox 中測試):

<form onsubmit="event.preventDefault(); validateMyForm();">

其中 validateMyForm() 是一個在驗證失敗時返回false的函數。 關鍵點是使用名稱event 我們不能使用例如e.preventDefault()

基於@Vikram Pudi 的回答,我們也可以使用純 Javascript 來做這樣的事情

<form onsubmit="submitForm(event)">
    <input type="text">
    <input type="submit">
</form>

<script type="text/javascript">

    function submitForm(event){
        event.preventDefault();


    }
</script>

只需使用一個簡單的button而不是提交按鈕。 並調用一個 JavaScript 函數來處理表單提交:

<input type="button" name="submit" value="submit" onclick="submit_form();"/>

script標簽內的函數:

function submit_form() {
    if (conditions) {
        document.forms['myform'].submit();
    }
    else {
        returnToPreviousPage();
    }
}

你也可以試試window.history.forward(-1);

做一件簡單的事有很多困難的方法:

<form name="foo" onsubmit="return false">

你所有的答案都提供了一些可以使用的東西。

最后,這對我有用:(如果您沒有選擇至少一個復選框項目,它會發出警告並停留在同一頁面上)

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <form name="helloForm" action="HelloWorld" method="GET"  onsubmit="valthisform();">
            <br>
            <br><b> MY LIKES </b>
            <br>
            First Name: <input type="text" name="first_name" required>
            <br />
            Last Name: <input type="text" name="last_name"  required />
            <br>
            <input type="radio" name="modifyValues" value="uppercase" required="required">Convert to uppercase <br>
            <input type="radio" name="modifyValues" value="lowercase" required="required">Convert to lowercase <br>
            <input type="radio" name="modifyValues" value="asis"      required="required" checked="checked">Do not convert <br>
            <br>
            <input type="checkbox" name="c1" value="maths"     /> Maths
            <input type="checkbox" name="c1" value="physics"   /> Physics
            <input type="checkbox" name="c1" value="chemistry" /> Chemistry
            <br>

            <button onclick="submit">Submit</button>

            <!-- input type="submit" value="submit" / -->
            <script>
                <!---
                function valthisform() {
                    var checkboxs=document.getElementsByName("c1");
                    var okay=false;
                    for(var i=0,l=checkboxs.length;i<l;i++) {
                        if(checkboxs[i].checked) {
                            okay=true;
                            break;
                        }
                    }
                    if (!okay) { 
                        alert("Please check a checkbox");
                        event.preventDefault();
                    } else {
                    }
                }
                -->
            </script>
        </form>
    </body>
</html>

我建議不要使用onsubmit而是在腳本中附加一個事件。

var submit = document.getElementById("submitButtonId");
if (submit.addEventListener) {
  submit.addEventListener("click", returnToPreviousPage);
} else {
  submit.attachEvent("onclick", returnToPreviousPage);
}

然后使用preventDefault() (或returnValue = false對於舊瀏覽器)。

function returnToPreviousPage (e) {
  e = e || window.event;
  // validation code

  // if invalid
  if (e.preventDefault) {
    e.preventDefault();
  } else {
    e.returnValue = false;
  }
}

假設您有一個類似於此的表格

<form action="membersDeleteAllData.html" method="post">
    <button type="submit" id="btnLoad" onclick="confirmAction(event);">ERASE ALL DATA</button>
</form>

這是confirmAction函數的javascript

<script type="text/javascript">
    function confirmAction(e)
    {
        var confirmation = confirm("Are you sure about this ?") ;

        if (!confirmation)
        {
            e.preventDefault() ;
            returnToPreviousPage();
        }

        return confirmation ;
    }
</script>

這適用於 Firefox、Chrome、Internet Explorer(edge)、Safari 等。

如果不是這樣,請告訴我

例如,如果您在表單上有提交按鈕,為了停止它的傳播,只需編寫 event.preventDefault(); 在單擊提交按鈕或輸入按鈕時調用的函數中。

干脆做吧......

<form>
<!-- Your Input Elements -->
</form>

這里是你的 JQuery

$(document).on('submit', 'form', function(e){
    e.preventDefault();
    //your code goes here
    //100% works
    return;
});

Hemant 和 Vikram 的答案在 Chrome 中並不完全適合我。 event.preventDefault(); 無論是否通過驗證,腳本都會阻止頁面提交。 相反,我不得不移動 event.preventDefault(); 進入if語句如下:

    if(check if your conditions are not satisfying) 
    { 
    event.preventDefault();
    alert("validation failed false");
    returnToPreviousPage();
    return false;
    }
    alert("validations passed");
    return true;
    }

感謝 Hemant 和 Vikram 讓我走上正軌。

禁用提交按鈕也有助於防止表單提交。

<input style="display:none" type="submit" disabled>

盡管看起來很明顯,但應該注意的是,如果您使用阻止默認值阻止提交,如果驗證順利進行,您還必須提交您的表單。 我在下面提供了一個完整的示例來驗證文檔類型,然后提交是否正確的文檔類型。

<h2>Document Upload</h2>
<script>
var CanContinue = false;

function validateMyForm()
{
if(CanContinue == false)
  { 
    alert("You must upload a PDF, PNG, or JPG of your document.");


return false;

  }
  document.getElementById("myForm").submit();

  return true;
}

function getFileNameWithExt(event) {

  if (!event || !event.target || !event.target.files || event.target.files.length === 0) {
return;
  }

  const name = event.target.files[0].name;
  const lastDot = name.lastIndexOf('.');

  const fileName = name.substring(0, lastDot);
  const ext = (name.substring(lastDot + 1)).toUpperCase();
    if (ext =="JPG") {
    extension.value = "image/jpeg";
    CanContinue = true;

} else if (ext =="JPEG") {
  extension.value = "image/jpeg";
  CanContinue = true;

} else if (ext =="PNG") {
  extension.value = "image/png";
  CanContinue = true;

} else if (ext =="PDF") {
  extension.value = "application/pdf";
  CanContinue = true;

} else {
  alert("You must upload a PDF, PNG, or JPG of your document.");
  CanContinue = false;
}

  outputfile.value = fileName;


}

</script>


                <form method="post" id="myForm" action="/wheregoing" enctype="multipart/form-data" onsubmit="event.preventDefault(); validateMyForm();">
                
                Please upload a JPG, PNG, or PDF of the front of the document.
                <input id='inputfile' type="file" name="dafile" onChange='getFileNameWithExt(event)' required>
               
             <input id='extension' type='hidden' name='ContentType' value="">
                <input type="submit">
                </form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM