Sunday, February 23, 2014

HTML Forms With Single Text Input - Fail!

This is probably old news, but I learned the hard way.
I have some simple forms with tables, select lists, buttons and in three cases, just a single text field.  I needed to validate the text field, so I added a javascript onChange function.  All my buttons have onClick functions.  But, if the user enters characters (that need validation) in the text field and hits the {Enter} key, none of my validation took place.  
I tried a dozen different approaches then did a Google search.  It turns out that the specification for HTML was modified with this requirement -- 
If a form has a single text input field, then the {Enter} key acts as a form submit().
No, it doesn't go through your field onChange method, nor through your focused button onClick method.  It goes straight to form submit.

Naturally, the solution is to put your form validation in a form onSubmit method.
But, why is bypassing all other controls / validation perceived as a "convenience"?
Here's a simplified example (save as html and load in Your browser). 
To see the difference when there are more than one text field, uncomment the second one and reload.

<HTML>
<HEAD>
<!-- Active content stripped -->
</HEAD>
<BODY>
<FORM NAME='myForm' onsubmit='return validateForm(this);'>
<INPUT TYPE='text' NAME='inText' onChange='tryValidate()' />
<INPUT TYPE='button' VALUE='Change' onClick='tryValidate()' />

<!--
<INPUT TYPE='text' />
// -->

</FORM>
</BODY>
</HTML>

1 comment: