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.
Create a “menu.js” script file, and include it using:
script type="text/javascript" src="menu.js"></script>
Create a function called “verifyOrder” in that file.
function verifyOrder(form) {
var customerField = form["customer"];
if (!customerField.value) {
customerField.style.backgroundColor = "red";
window.alert("We need your name in order to deliver your order.");
return false;
} else {
customerField.style.backgroundColor = "inherit";
return true;
}
}
Add “onsubmit="return verifyOrder(this);"” to the <form> tag in the HTML page.
When you submit the form without filling out your name, it will display an alert box explaining that the name is required, and it will color the name input box red. If you type something into the name field and then submit, then the browser will submit the form to the form’s “action” (in this case, showing “Not Implemented”).
Form inputs and values
You can get a form’s input elements using the same method you would to get an element from an array. If there’s an input called “customer”, then form["customer"] is that element. We can even change the style on that element just as we would for any other element.
Input elements have a “value” property. This property contains the value of that element. If the customer has typed something into the element, the value property will be what they typed.
Customer name required: onsubmit
One of the attributes that <form> tags can have is onsubmit. The onsubmit attribute must contain JavaScript, and that JavaScript is performed when the form is submitted. If that JavaScript returns true, the form is submitted. If that JavaScript returns false, the form is not submitted. The verifyOrder function returns false if the customer field is empty, or true otherwise.
Remember, “this” in a tag is that tag. Since the “onsubmit” is in the <form> tag, “this” means that specific form. When it gets passed as the first parameter to “verifyOrder”, the first parameter in verifyOrder is called “form”.