Skip to main content | Turn off styling Default page style

Question & Answer index

Working with Select Boxes

The question about how to handle select boxes comes up so often, that I'm dedicating an entire page to show how to get values and how validation should be done.

Here is a quick look at how to write a function using javascript to return the selected value of a select box.

In this function there is an optional parameter "retType". If you want the text of the option the user selected, pass 'text' in as a second parameter.

For this demo, let's presume you have one question with 4 options and the user must select at least one answer, such as the following:

How many pecks are in a bushel?
validate

Here is the HTML for the question setup and the call to the validation function.

Here is how the validation looks - notice that there are 3 main functions involved.

There are 4 additional functions that are used to control displaying the error message:

Though a bit tedious for such a short demo as this, in order to maximize reusability, validation is its own function and the validation of each question is its own function. This approach has three main advantages over putting everything in one function:

  1. minimizes the number of times you must repeat the same lines of code (the "get" function)
  2. makes it easier and safer to modify validation methods later, including changes required for when you change question type (radio to select box, etc.)
  3. keeps the validation logic "clean" so it is easy to interpret and work with