Validating Select Menus

Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.

Contact Us or call 1-877-932-8228
Validating Select Menus

Validating Select Menus

Select menus contain an array of options. The selectedIndex property of a select menu contains the index of the option that is selected. Often the first option of a select menu is something meaningless like "Please choose an option..." The checkSelect() function in the example below makes sure that the first option is not selected.

Code Sample:

<meta charset="UTF-8">
<title>Select Menus</title>
function validate(e){
	var errors = [];
	if (!checkSelect(document.getElementById("flavor")) ) {
		errors[errors.length] = "You must choose a flavor.";
	if (errors.length > 0) {


function checkSelect(select){
	return (select.selectedIndex > 0);
function reportErrors(errors){
	var msg = "There were some problems...\n";
	var numError;
	for (var i=0; i<errors.length; i++) {
		numError = i + 1;
		msg += "\n" + numError + ". " + errors[i];

window.onload = function() {
	document.getElementById("flavorform").addEventListener("submit", function(e){
<h1>Ice Cream Form</h1>
<form method="post" action="Process.html" id="flavorform">
	<select name="flavor" id="flavor">
		<option value="0" selected></option>
		<option value="choc">Chocolate</option>
		<option value="straw">Strawberry</option>
		<option value="van">Vanilla</option>
	<input type="submit" value="Place Order">

This tutorial is based on Webucator's Introduction to JavaScript Training Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.