[thelist] disabling enter on form

jeff jeff at members.evolt.org
Sun Nov 26 20:51:44 CST 2000


michele,

:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
: From: Michele Foster
:
: Is there anything I can do that would disable
: the submit via pressing enter?
:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

sure, simply attach some form validation to the form and hitting enter will
fire the form's onsubmit event handler, checking the data, and halting
submission if it doesn't meet your validation criteria.

:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
: Can hitting enter cycle through the different field
: elements like pressing tab does?
:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

no, nor should it.  users have come to expect a certain type of behavior
with form elements.  tab moves between fields and enter submits (in most
cases).  to catch these and cause different behavior would be confusing.

now, about that form validation.  it's rather simple.  use the form's
onsubmit event handler, calling your validation function like this:

return validateForm(this)

your validateForm() function will return a value of true if all the data
validates or it will return false if any of it fails.  the call to the
function is then effectively replaced by the value the function returns
yielding a return statement that the browser can act upon.  a statement of
"return true" tells the browser to continue with what it was doing -
submitting.  a statement of "return false" tells the browser to stop what
it's doing.

assuming your validating whether there is data in a login form (username &
password), this is what your validateForm() function might look like:

function validateForm(form)
{
  if(!form.username.value)
  {
    alert('Username is required.');
    form.username.focus();
    return false;
  }
  if(!form.password.value)
  {
    alert('Password is required.');
    form.password.focus();
    return false;
  }
  return true;
}

your form would look like this:

<form action="..." method="post" onSubmit="return validateForm(this)">
  <input type="text" name="username" value="">
  <input type="password" name="password" value="">
  <input type="submit">
</form>

good luck,

.jeff

name://jeff.howden
game://web.development
http://www.evolt.org/
mailto:jeff at members.evolt.org





More information about the thelist mailing list