简体   繁体   中英

Submit form using specific button

I have a page with many forms and each form may has more than one submit button and each button has some actions " onclick " which specified by html.

I have created handler onclick via jquery for submit buttons which prevent default action and doing some work but then I need to submit this form. If i just simulate click on button - all actions triggered to onclick works once again.

Any ideas about it?

Abstract code example:

<form>
  <input type='submit' name='first_button' onclick='doSomething()'>
  <input type='submit' name='second_button' onclick='doSomethingElse()'>
<form>

Just call referenceToFormElement.submit() .

Since your submit buttons don't have values, you can't care about the server knowing which one was clicked, so bypassing them when submitting the form with JS will be fine.

 document.querySelector("[name=first_button]").addEventListener('click', doSomething); document.querySelector("[name=second_button]").addEventListener('click', doSomethingElse); function doSomething(e) { var button = this; e.preventDefault(); setTimeout(function() { alert("Submitting A!"); button.form.submit(); }, 1000); } function doSomethingElse(e) { var button = this; e.preventDefault(); setTimeout(function() { alert("Submitting B!"); button.form.submit(); }, 1000); } 
 <form> <input type='submit' name='first_button'> <input type='submit' name='second_button'> </form> <p>(NB: This won't actually submit because it is on Stackoverflow: Blocked form submission to 'http://stacksnippets.net/js' because the form's frame is sandboxed and the 'allow-forms' permission is not set.) 

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