简体   繁体   中英

Form onSubmit function not firing when form submitted

I have had a look and cannot find anything like my problem.

I have a form where I cannot get the validation to work. I know the JavaScript file is loading since other functions on the page are working without issue. My code is as follows:

  <form method="post" name="selectMod" action="check.php" onsubmit="validate()">

There is then the form and the button is coded as follows:

  <div class="form-row">
                <div class="col-sm-12 col-md-12">
                    <button type="submit" class="btn btn-success btn-block center-block">Submit</button>

At the moment the code in the function is set to just return false since I cannot get it to work.

  function validate(){
  return false;
  }

Sure I am missing something obvious but cannot see what it is.

It is firing. It just doesn't do anything with observable effects.

  1. The onsubmit function calls validate
  2. The validate function returns false (because it has a return statement)
  3. The onsubmit function ignores that return value
  4. The onsubmit function returns undefined (because it doesn't have a return statement

If you want to prevent the default behaviour of the submit event, then you need to return false from the onsubmit function

onsubmit="return validate()"

Modern code would avoid intrinsic event attributes in favour of binding event listers with JavaScript and manipulating the event object.

var myForm = document.querySelector("form");
myForm.addEventListener("submit", validate);
function validate(event) {
    event.preventDefault();
}

You can use following:

 function validate(){
    //if check false
    event.preventDefault();
    return false;
 }

在 check() 函数中, getEforlementById语法无效

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM