May 262014
 
Article HTML

In some HTML forms we may find dropdown (<select>) elements with a high number of entries. To make the dropdown more user friendly, the entries might be grouped by some relevant criteria.

Using static HTML to group entries in a dropdown

Let’s use a sample form with a <select> dropdown to choose a country from a list. The HTML code of the dropdown could be like this:

But countries can be grouped using different criteria: The continent they belong to, the official language,…

The tag <optgroup> can be added to the HTML code to group countries by the chosen criterion. For instance, in order to group countries by language, we would rewrite the HTML code in our sample as follows:

And we will get the resulting dropdown as:

Using javascript to dynamically group entries in a dropdown

It is also possible to use a javascript function that will run on page load, and will rewrite the content of a dropdown, grouping the entries by some criterion.

The following built-in functions will be used:

  • document.getElementByID – Get a reference to the “select” element
  • getElementByTagName –  Get an array holding the entries (<option>…</option>) in the “select” element.
  • createElement(“optgroup”), optgroup.setAttribute(“label”) – Create a new “optgroup” element
  • appendChild, removeChild – Add and remove subelements from the select element and the optgroup subelements

The sample function below groups entries in the dropdown by the starting character:

References

 Posted by at 9:47 am

 Leave a Reply

(required)

(required)