Cookies improve the way our website works, by using this website you are agreeing to our use of cookies. For more information see our privacy policy.
OK
The onsubmit event is commonly used to validate the contents of form controls and set the contents of some input:hidden elements before submitting.
If the user forgot to fill some required fields or made some other mistake on the form, you can cancel the submission with the onsubmit event.
See the example below for details.
The event object is accessible to all event handlers in all browsers.
The properties of the event object contain additional information about the current event.
To get further details about these properties and the possible event handler registration methods, please see the page for the event object.
This example illustrates the use of the onsubmit event:
<head><scripttype="text/javascript">function CheckAndSubmit () {
var userName = document.getElementById ("userName");
if (userName.value.length < 3) {
alert ("The name of the user must be at least 3 characters long!");
returnfalse;
}
var password = document.getElementById ("password");
var repassword = document.getElementById ("repassword");
if (password.value.length < 6) {
alert ("The password must be at least 6 characters long!");
returnfalse;
}
if (repassword.value != password.value) {
alert ("The two passwords are different!");
returnfalse;
}
var acceptAgreement = document.getElementById ("acceptAgreement");
if (!acceptAgreement.checked) {
alert ("You must accept the User Agreement to register!");
returnfalse;
}
returntrue;
}
</script></head><body><formid="regForm"method="post"action="#URL#"onsubmit="return CheckAndSubmit ()">
User Name: <inputtype="text"name="userName"id="userName"/><br/>
Password: <inputtype="password"name="password"id="password"/><br/>
Repeat Password: <inputtype="password"name="repassword"id="repassword"/><br/><br/><inputtype="checkbox"name="acceptAgreement"id="acceptAgreement"/><labelfor="acceptAgreement">I accept the User Agreement and Privacy Policy</label><br/><br/><inputtype="submit"value="Register"/></form></body>
This example and the next one use AJAX to submit a form without reloading the page. The two examples are similar, but the first one uses synchronous while the second one uses asynchronous data transfer. In synchronous mode, the send method of the XMLHttpRequest object waits for a reply, so the user cannot interact with the browser until the response has completed. In asynchronous mode, the send method does not wait for a reply but instead returns immediately, so it allows you to perform other operations while a time-consuming task is being performed in the background.
Code
ajax_form.js
register.php
<head><scripttype="text/javascript"src="ajax_form.js"></script><style>.error {
display: none;
color: #a00000;
font-weight: bold;
}
</style><scripttype="text/javascript">function HideAllErrorFields () {
for (var i = 1; i <= 4; i++) {
var field = document.getElementById ("error" + i);
field.style.display = "none";
}
}
function ShowErrorFields (idsStr) {
var ids = idsStr.split (",");
for (var i = 0; i < ids.length; i++) {
var field = document.getElementById ("error" + ids[i]);
if (field) {
field.style.display = "block";
}
}
}
function AjaxSend (form, url, method) {
// hide all error fields
HideAllErrorFields ();
// get message data
var data = GetMessageBody (form); // defined in ajax_form.js
// send the request
var httpRequest = CreateRequestObj (); // defined in ajax_form.js
// try..catch is required if working offline
try {
httpRequest.open (method, url, false); // synchron
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.send (data);
}
catch (e) {
alert ("Cannot connect to the server!");
return;
}
// handle the response
if (IsRequestSuccessful (httpRequest)) { // defined in ajax_form.js
if (httpRequest.responseText === "ok") { // registration is successful
alert ("Thank you for registering");
/*
// if redirection is required
location.href = "/index.php";
*/
}
else { // some fields are invalid
ShowErrorFields (httpRequest.responseText);
}
}
else {
alert ("An error occurred while registering. Please try it again.");
}
}
</script></head><body>
This is a sample registration form.
The username must be between 2 and 20 characters, the password must be between 6 and 20 characters.
A user named Dottoro is already registered.
<br/>
Try to register both valid and invalid values!
<br/><br/><formonsubmit="AjaxSend (this, 'register.php', 'post'); return false;">
User Name: <inputtype="text"name="userName"/><divclass="error"id="error1">Must be between 2 and 20 characters.</div><divclass="error"id="error2">A user already exists with the same name.</div><br/><br/>
Password: <inputtype="password"name="password"/><divclass="error"id="error3">Must be between 6 and 20 characters.</div><br/><br/>
Repeat Password: <inputtype="password"name="repassword"/><divclass="error"id="error4">Must be the same as the password.</div><br/><br/><inputtype="submit"value="Register"/></form></body>
function CreateRequestObj () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
returnnewXMLHttpRequest();
}
else {
try {
returnnewActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
}
// create HTTP request body form form data
function GetMessageBody (form) {
var data = "";
for (var i = 0; i < form.elements.length; i++) {
var elem = form.elements[i];
if (elem.name) {
var nodeName = elem.nodeName.toLowerCase ();
var type = elem.type ? elem.type.toLowerCase () : "";
// if an input:checked or input:radio is not checked, skip it
if (nodeName === "input" && (type === "checkbox" || type === "radio")) {
if (!elem.checked) {
continue;
}
}
var param = "";
// select element is special, if no value is specified the text must be sent
if (nodeName === "select") {
for (var j = 0; j < elem.options.length; j++) {
var option = elem.options[j];
if (option.selected) {
var valueAttr = option.getAttributeNode ("value");
var value = (valueAttr && valueAttr.specified) ? option.value : option.text;
if (param != "") {
param += "&";
}
param += encodeURIComponent (elem.name) + "=" + encodeURIComponent (value);
}
}
}
else {
param = encodeURIComponent (elem.name) + "=" + encodeURIComponent (elem.value);
}
if (data != "") {
data += "&";
}
data += param;
}
}
return data;
}
// returns whether the HTTP request was successful
function IsRequestSuccessful (httpRequest) {
// IE: sometimes 1223 instead of 204
var success = (httpRequest.status == 0 ||
(httpRequest.status >= 200 && httpRequest.status < 300) ||
httpRequest.status == 304 || httpRequest.status == 1223);
return success;
}
This example is similar to the previous one, but it uses asynchronous data transfer and displays blinking text while waiting for the server response (the register_delay.php script waits two seconds before responding).
Code
ajax_form.js
register_delay.php
<head><scripttype="text/javascript"src="ajax_form.js"></script><style>.error {
display: none;
color: #a00000;
font-weight: bold;
}
#progress {
visibility: hidden;
color: #00a000;
}
</style><scripttype="text/javascript">function HideAllErrorFields () {
for (var i = 1; i <= 4; i++) {
var field = document.getElementById ("error" + i);
field.style.display = "none";
}
}
function ShowErrorFields (idsStr) {
var ids = idsStr.split (",");
for (var i = 0; i < ids.length; i++) {
var field = document.getElementById ("error" + ids[i]);
if (field) {
field.style.display = "block";
}
}
}
var registering = false;
function OnReadyStateChanged (httpRequest, form) {
if (httpRequest.readyState == 0 || httpRequest.readyState == 4) {
registering = false;
StopAnim ();
// prevent memory leaks
httpRequest.onreadystatechange = null;
if (IsRequestSuccessful (httpRequest)) { // defined in ajax_form.js
if (httpRequest.responseText === "ok") { // registration is successful
alert ("Thank you for registering");
/*
// if redirection is required
location.href = "/index.php";
*/
}
else { // some fields are invalid
ShowErrorFields (httpRequest.responseText);
}
}
else {
alert ("An error occurred while registering. Please try it again.");
}
}
}
function AjaxSend (form, url, method) {
// avoid resend data while registering
if (registering) {
return;
}
// hide all error fields
HideAllErrorFields ();
// get message data
var data = GetMessageBody (form); // defined in ajax_form.js
// send the request
var httpRequest = CreateRequestObj (); // defined in ajax_form.js
// try..catch is required if working offline
try {
httpRequest.open (method, url, true); // asynchron
httpRequest.onreadystatechange = function () {OnReadyStateChanged (httpRequest, form)};
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.send (data);
}
catch (e) {
alert ("Cannot connect to the server!");
return;
}
registering = true;
StartAnim ();
}
// blinking text
var animTimerId = 0;
function StartAnim () {
var progress = document.getElementById ("progress");
progress.style.visibility = "visible";
animTimerId = setInterval (RegAnim, 100);
}
function RegAnim () {
var progress = document.getElementById ("progress");
progress.style.visibility = (progress.style.visibility == "visible") ? "hidden" : "visible";
}
function StopAnim () {
var progress = document.getElementById ("progress");
progress.style.visibility = "hidden";
clearInterval (animTimerId);
}
</script></head><body>
This is a sample registration form.
The username must be between 2 and 20 characters, the password must be between 6 and 20 characters.
A user named Dottoro is already registered.
<br/>
Try to register both valid and invalid values!
<br/><br/><formonsubmit="AjaxSend (this, 'register_delay.php', 'post'); return false;">
User Name: <inputtype="text"name="userName"/><divclass="error"id="error1">Must be between 2 and 20 characters.</div><divclass="error"id="error2">A user already exists with the same name.</div><br/><br/>
Password: <inputtype="password"name="password"/><divclass="error"id="error3">Must be between 6 and 20 characters.</div><br/><br/>
Repeat Password: <inputtype="password"name="repassword"/><divclass="error"id="error4">Must be the same as the password.</div><br/><br/><inputtype="submit"value="Register"/><divid="progress">Registering</div></form></body>
function CreateRequestObj () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
returnnewXMLHttpRequest();
}
else {
try {
returnnewActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
}
// create HTTP request body form form data
function GetMessageBody (form) {
var data = "";
for (var i = 0; i < form.elements.length; i++) {
var elem = form.elements[i];
if (elem.name) {
var nodeName = elem.nodeName.toLowerCase ();
var type = elem.type ? elem.type.toLowerCase () : "";
// if an input:checked or input:radio is not checked, skip it
if (nodeName === "input" && (type === "checkbox" || type === "radio")) {
if (!elem.checked) {
continue;
}
}
var param = "";
// select element is special, if no value is specified the text must be sent
if (nodeName === "select") {
for (var j = 0; j < elem.options.length; j++) {
var option = elem.options[j];
if (option.selected) {
var valueAttr = option.getAttributeNode ("value");
var value = (valueAttr && valueAttr.specified) ? option.value : option.text;
if (param != "") {
param += "&";
}
param += encodeURIComponent (elem.name) + "=" + encodeURIComponent (value);
}
}
}
else {
param = encodeURIComponent (elem.name) + "=" + encodeURIComponent (elem.value);
}
if (data != "") {
data += "&";
}
data += param;
}
}
return data;
}
// returns whether the HTTP request was successful
function IsRequestSuccessful (httpRequest) {
// IE: sometimes 1223 instead of 204
var success = (httpRequest.status == 0 ||
(httpRequest.status >= 200 && httpRequest.status < 300) ||
httpRequest.status == 304 || httpRequest.status == 1223);
return success;
}