Display all required fields

  1. Order required
  2. Menu form
  3. Today’s special

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.

function verifyOrder(form) {

var customerField = form["customer"];

var warnings = new Array();

if (!(

radioValue(form, 'drinks') ||

radioValue(form, 'sides') ||

radioValue(form, 'dishes'))

) {

document.getElementById('orders').style.backgroundColor = "red";

warnings.push("Please choose something to eat and/or drink.");

} else {

document.getElementById('orders').style.backgroundColor = "inherit";

}

if (!customerField.value) {

customerField.style.backgroundColor = "red";

warnings.push("We need your name in order to deliver your order.");

} else {

customerField.style.backgroundColor = "inherit";

}

if (warnings.length) {

warnings = warnings.join("\n");

window.alert(warnings);

return false;

} else {

return true;

}

}

Now, if you leave off both an order and your name, you’ll see the two errors all at once, and both sections of the form will be highlighted.

Array.push and Array.join

We’re using two of the more useful methods of Arrays here: push and join. Array.push adds a new item to the end of the list. Array.join(character) joins each item of the array together into a string of text, separating each item by the character we gave join as a parameter.

Display all required fields: \n

Backslash-n is commonly used to make a new line. When you have “\n” in a string of text, JavaScript replaces those two characters with a newline character instead. You’ll use “\n” often when joining arrays. Backslashes are used for other special characters, too. If you need a tab, you can use “\t”. If you really do want a backslash, use two backslashes: “\\”.

  1. Order required
  2. Menu form
  3. Today’s special