Ajax and form submission

7.17.07

Situation: You have a form which you would like to validate before submitting. you also want to show error messages without having to reload the page. Example:

<form name="login">
<label for="user">Username</lable><input type="text" name="user">
<label for="password">Password</label><input type="password" name="password">
<input type="button" value="Login">
</form>

Suppose you want to call a function called validate() when either the user presses enter or clicks the button. The trick I discovered with Prototype is as follows:

function checkForSubmission(element,func){
Event.observe(element, 'keypress', function(event){
if(event.keyCode==13)
func();
});
}

Now for the example above, when the page loads you simply call

checkForSubmission("login",validate);

If the user presses enter in any of the two text boxes or clicks the button the form will now validate itself. Simple solution to a tricky situation.

Update: It seems that in Safari events happen in a different order: onSubmit event takes place before the onKeyPress event. To get around this you need to return false when onSubmit occurs. Easiest solution is to add the following to the form tag.

onSubmit="return false;"