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:
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.
- Validation() - makes calls to other functions to validate each specific question
- ValidatePecksInABushel(selectBox) - the function that determines whether a questions is answered correctly or not
- getSelectedValue(selectbox,retType) - the function that we will use to get the value for any selectBoxes on our page
There are 4 additional functions that are used to control displaying the error message:
- updateQuestionMessage(field,hasError,message) - if you are displaying an error on the page, this funtion adds the message to the page and makes the text red.
- safeGetElementByID(field) - a helper function that allows me to quickly verify that an element exists on the page.
- setErrorClass(field) - used for adding the class error to the element.
- removeErrorClass(field) - used for adding the class error to the element.
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:
- minimizes the number of times you must repeat the same lines of code (the "get" function)
- makes it easier and safer to modify validation methods later, including changes required for when you change question type (radio to select box, etc.)
- keeps the validation logic "clean" so it is easy to interpret and work with