简体   繁体   中英

submit function does not trigger onsubmit return function?

I think I have a misunderstanding of the onsubmit attribute. I thought that every submission, like a <input type="submit" ...> , <button></button> or any javascript form.submit() trigger the onsubmit="return function();" after the submit. In other words, I will never see the "last triggered" log.

Example:

 function triggerFirst() { console.log("first triggered"); myForm.submit(); } function triggerLast() { console.log("last triggered"); return true; } 
 <form id="myForm" onsubmit="return triggerLast();"> <input type="button" onclick="triggerFirst();" value="trigger"> </form> 

This example will never trigger the onsubmit, why? I thought onsubmit means if someone submits? Is that false?

It works.

UPDATED: Place the 2nd function inside first.

 function triggerFirst() { alert('wow'); triggerLast() } function triggerLast() { alert('wowpsubmit'); return true; } 
 <form id="myForm" onsubmit='return triggerLast();'> <input type="button" onclick="triggerFirst();" value="trigger" > </form> 

An HTML form does not require javascript to work. Refer the code below:

<form action="action_page.php">
  First name:<br>
  <input type="text" name="firstname" value="Mickey"><br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse"><br><br>
  <input type="submit" value="Submit">
</form>

The <form action="action_page.php"> declaration is run once the form is submitted.

The <input type="submit" value="Submit"> is a built in type that triggers the form action to run.

See more here

In your triggerFirst function the inner function call to submit does nothing. That submit function is not defined. I think here you want to make the function submit so below I passed a reference to the form into the triggerFirst function. This should clarify things for you. Open the console to view the output.

 function triggerFirst(form) { console.log('triggerFirst') console.log(form); form.submit(); } function triggerLast() { console.log('triggerLast') return true; } 
 <form onsubmit="return triggerLast();"> <input type="button" onclick="triggerFirst(this.form);" value="trigger"> </form> 

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