Share this Page URL

Chapter 18. More JavaScript Fun > JavaScript and Forms - Pg. 212

More JavaScript Fun 212 Making Form Fields Mandatory One of the problems we webmasters face when constructing forms is getting our users to fill in all the required fields. We can augment the form with all kinds of notes that warn the user of the dire consequences that can result from leaving a field blank, but users have a way of ignoring these things. A better approach is to use a little JavaScript know-how to make one or more form fields mandatory. That is, make it so the browser won't submit the form unless the user puts something in those fields. For example, there isn't any way for my MailForm script (see Chapter 12) to detect the user's e-mail address, which means you have to rely on your readers to enter their e-mail address so that you can contact them. One thing you can do is use JavaScript to make your form's e-mail field manda- tory. To set this up, you first need to make two adjustments to your <FORM> tag: · Add the NAME attribute and set it to whatever you want to name your form. · Add the JavaScript onSubmit attribute, like so (here, FormName is the name you gave your form). onSubmit="return Validate(FormName)" Here's an example: <FORM ACTION="" METHOD="POST" NAME="MyForm" onSubmit="return Validate(MyForm)">