javascript - What is the difference between onsubmit="submitForm();" and onsubmit="return submitForm();" -


does example below mean form submitted twice?

<form name="myform" action="demo_form.asp" onsubmit="submitform();" method="post">  function submitform(){    document.myform.submit(); } 

i have bug records 2 of each record sometimes. , i'm suspecting because form submitting twice

onsubmit="" on form element defines event function. return value, if defined, passed browser. falsy value (false, null, undefined, etc.) prevent browser proceeding form submission.

it's similar other functions

function isvalid(form) {   if (somebadcondition) {     // record error somewhere     return false;   }   if (somehorriblecondition || someequallybadcondition) {     // record other error     return false;   }   return true; }  function cansubmitform(form) {   isvalid(form); } 

the last line never passes return value back. therefore

console.log(isvalid(someform));  // true console.log(cansubmitform(someform));  // undefined 

think of onsubmit="submitform()" being cansubmitform. is. whatever define in onsubmit="" evaluated function answer question "can submit this?".

you fix above example like:

function cansubmitform(form) {   return isvalid(form); } 

notice return statement pass result of isvalid through caller of cansubmitform.

therefore, diffrence between

onsubmit="submitform();" 

and

onsubmit="return submitform();" 

is in former, return value of submitform ignored. in later example, if submitform return value, passed caller of onsubmit, browser.

you submitting form twice because code says "when submitting form, submit form".

if submitform javascript function needs own submitting process (common thing ajax w/ graceful degradation), need add return false in event handler.

onsubmit="submitform(); return false" 

or change submitform return false , onsubmit pass on

onsubmit="return submitform();"  function submitform() {   // submission stuff   return false; } 

i recommend former, put explicit false in event handler. reason event handler reason false needed. submitting isn't false. didn't somehow fail or reject. submitform should focus on submission stuff , let event handler handle browser event handling stuff. plus error-proofs code bit.


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -