简体   繁体   中英

How do I stop the second onclick function from happening while the first function is executing?

I'm currently working on a validation feature. If the form fails to validate, it won't be able to submit, hence, I need to figure out a way to prevent the submitFilloutform() from happening.

<button 
  id="submit" 
  name="submit"
  type="submit"
  class="btn btn-warning"
  style="float: right;"
  onclick="validateForm(), submitFilloutform()"
>Submit</button>

Any help would be greatly appreciated. Thanks!

EDIT: I came back to this as someone upvoted it (thanks). One consideration to add it that inline JS may be a bad idea in the case that you want to lock down potential for cross-site-scripting attacks. Part of the defence of that is CSP headers and one strong contender to set is a rule that bans all inline JS. So, if you plan to use CSP you might want to move the JS below into an onclick listener for id=submit in a separate JS file.

Original answer.

onClick is executed like a function, so can include JS logic. Such as...

<button 
  id="submit" 
  name="submit" 
  type="submit"  
  class="btn btn-warning" 
  style="float: right;" 
  onclick="if (validateForm()){ submitFilloutform();}"
>
Submit
</button>

This assumed that validateForm() returns a boolean value, of course.

Why not invoke the second function at the end block inside the first function?

<button 
  id="submit"
  name="submit"
  type="submit"
  class="btn btn-warning"
  style="float: right;"
  onclick="validateForm()"
>Submit</button>

function validateForm() {
  // xxx
  submitFilloutform()
}

function submitFilloutform() {
  // xxx
}

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