JavaScript code to stop form submission

前端 未结 12 2280
感情败类
感情败类 2020-11-21 06:40

One way to stop form submission is to return false from your JavaScript function.

When the submit button is clicked, a validation function is called. I have a case i

12条回答
  •  萌比男神i
    2020-11-21 07:02

    I would recommend not using onsubmit and instead attaching an event in the script.

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

    Then use preventDefault() (or returnValue = false for older browsers).

    function returnToPreviousPage (e) {
      e = e || window.event;
      // validation code
    
      // if invalid
      if (e.preventDefault) {
        e.preventDefault();
      } else {
        e.returnValue = false;
      }
    }
    

提交回复
热议问题