JavaScript is often used in forms to provide feedback and guidance to the person filling out the form. Open “menu.html” in your browser, and think about what we might do to make this form easier to use. Note that because this is a tutorial about JavaScript and not about server-side code, form submission is disabled. One thing you can do to test it out is replace the javascript block in the form’s “action” attribute with “mailto:youremail”. When you submit the form, your browser will either send it via your e-mail software, or it will send it directly via e-mail. E-mailed form submissions aren’t often readable, however, so you may be better just leaving it as “Not Implemented”.
- Customer name required
- Probably the most common use of JavaScript for forms is to require one or more fields to be filled out. This form is meant for taking an order. There are two things that are required: something to eat or drink, and the customer’s name. Let’s do the name first, because it’s the easiest.
- Order required
- It doesn’t do much good to require a customer name without also requiring that the customer choose something to order. If you look at the HTML, there are three groups of radio buttons involved in ordering: the “drinks” group, the “sides” group, and the “dishes” group. We need to check to see that at least one of those items is checked.
- Display all required fields
- Currently, verifyOrder only displays one error at a time. But it’d be nice, if the customer missed two fields, to highlight both of them. But we don’t want to pop up a separate alert box for each warning. So we need to store the messages and display them all at once. We can use an Array to do this.
- Today’s special
- The bottom of the menu has a list of specials. You can see that the CSS for those lines is set to highlight the lines if the mouse moves over them. Why not, if a special is clicked, automatically select the items in the menu that correspond to that special?
- Favorite drink
- Everybody likes it when the bartender remembers their drink from last time. Let’s make our form remember it, too. Remembering things from past visits requires cookies. Cookies are bits of data stored on the client’s computer. The browser sends all of the cookies relevant to your page, every time it loads the page.