Steve0Greatness

Creating a HTML drop-down list

-

In order to create a drop-down selection list in HTML, we must first understand why they are important.

Drop-down lists can be used in lots of ways, from creating a way for people to chose from a strict set of options, to making an on-off switch(even though you should use buttons for that).

Before we start, here is an example:

Select Image:

Images from Wikipedia, on Oct. 2nd & 1st, 2021

For some weird reason, it's not in <input>, it has it's own tags: <select> and <option>. Using these is a little like making a list, if you've ever made one. Here's an example bit of HTML:

<select>
    <option>op 1</option>
    <option>op 2</option>
</select>

Like all inputs, select can have an id and name, and like input[type=radio], option can have a value.

However, you may not know some things that could be useful here, such as defaulting, or making things update upon being changed, well, you can do defaulting with selected in the <option> that you want to be preselected. Changes done the page upon the change of the selection in the drop-down(or anything else that can be changed by the user) is onchange="submitFunction()" being placed in the <select>.

Let's check back on the code that we made at the code example:

<select onchange="submitFunction()" id="selection">
    <option value="op1" selected>op 1</option>
    <option value="op2">op 2</option>
</select>

Inorder to access the selected option with JavaScript, use document.getElementById("selection").value.

That's basically it, feel free to CTRL + C CTRL + V it. /s