Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  47] [ 6]  / answers: 1 / hits: 48146  / 12 Years ago, thu, june 28, 2012, 12:00:00

Inside a form I have a button. What is the difference between when I submit the form via JavaScript like this



<button onclick=document.forms[0].submit();>


and when I submit it like this



<button type=submit></button>?


The first one works for me with most browsers except webkit-based. The latter works fine as well. No difference in functionality is apparent to me. Is there one?


More From » html

 Answers
29

The first example:



<button onclick=document.forms[0].submit();>


...will do two things:




  1. Its onclick will submit the first form in the document (i.e., the one specified by the 0 index in forms[0]).

  2. It will submit the form it is in (if it is in a form) because a button with no type attribute specified will be a submit button by default.



This two-step double-submit behaviour can be seen in this quick-and-dirty demo: http://jsfiddle.net/fMwuX/ (and is likely to lead to weird behaviour that might be a bit confusing to debug). If the button isn't actually in a form then this won't be a problem.



The second example:



<button type=submit></button>


Will simply submit the form it is in (if it is in one).



In my opinion the second option is definitely preferable for several reasons, including but not limited to:




  1. It will work even if the user has JS disabled.

  2. It doesn't hard-code a form index with forms[0].

  3. It is shorter and clearer.

  4. It won't clash with other form submit validation.


[#84602] Wednesday, June 27, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
milor

Total Points: 284
Total Questions: 93
Total Answers: 115

Location: Venezuela
Member since Thu, Jul 15, 2021
3 Years ago
;