+91-943-185-6038 me@shashidharkumar.com

When using JavaScript to check a form, the first thing you need is the onsubmit event handler. This event handler specifies a script that is executed when the user submits the form. That script is where you check whether certain fields have a value, whether the user has checked at least one checkbox, and any other checks you deem necessary.

The general syntax is:
<form action=”something.pl” onsubmit=”return checkscript()”>

                    where checkscript() is the name of the script. This script should return either true
or false. If false is returned, the form will not be submitted. If either true or false is returned the script stops.

                    So the general script becomes something like:

function checkscript()

{

 if (some value is/is not something)

{

 // something is wrong alert(‘alert user of problem’);

return false;

}

 else if (another value is/is not something)

{

 // something else is wrong alert(‘alert user of problem’);

return false;

}

 // If the script makes it to here, everything is OK,

 // so you can submit the form return true;

}

                    Of course this function can become much more complex if you have to check a complicated form with a lot of radio buttons and things. The general idea remains the same, however: You go through the elements, check whatever you want to check and as soon as you find any mistake, you return false, after which the script stops and the form is not submitted.

                    Once you’ve found a mistake, you should notify the user of the problem. This used to be done by an alert, but nowadays you can generate error messages and insert them next to the form field.

See also  Learn how to enable JavaScript in the most popular web browsers.

                    Only at the very end of the script, when you have checked all elements and encountered no mistakes, you return true, after which the form is submitted.