Main Page

Submitting forms

return;
}
}
}
};
This method can then be called in the
onload
event handler:
<body onload=”FormUtil.focusOnFirst()”>
Submitting forms
In regular HTML, you submit the form by using a Submit button or an image that acts like a Submit
button:
<input type=”submit” value=”Submit” /> <!-- submit button -->
<input type=”image” src=”submit.gif” /> <!-- image button -->
When the user clicks either one of these buttons, the form is submitted without requiring any additional
coding. If you press Enter on the keyboard when one of these types of buttons is present, the browser
submits the form as if the button were clicked.
You can test to see if a form is submitting by providing an alert for the
action
attribute:
<form method=”post” action=”javascript:alert(‘Submitted’)”>
This submits the form to the JavaScript function, which just pops up an alert with the word
“Submitted”
in it. This is helpful to test form submission because it doesn’t actually involve going back to the server.
If you want to submit the form without using one of the previously mentioned buttons, you can use the
submit()
method. The
submit()
method is part of the DOM definition of a
<form/>
element and can
be used anywhere on a page. To use this method, you must first get a reference to the
<form/>
element
either by using
getElementById()
or by using the
document.forms
collection. Each of the following
three lines is an acceptable way to reference a form:
oForm = document.getElementById(“form1”);
oForm = document.forms[“form1”];
oForm = document.forms[0];
After getting the form reference, you can just call the
submit()
method directly:
oForm.submit();
Be careful when using this method. In slow-loading pages, it is possible that the
user may start typing into a field before the page has been fully loaded. When the
focus is then set to the first field, it disrupts the user ’s input. To prepare for this
issue, first check for a value in the first field; if one is there, don’t set the focus to it.
340
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 340


JavaScript EditorFree JavaScript Editor     Ajax Editor


©