Cover Image for HTML List Box
58 views

HTML List Box

The HTML list box is created using the <select> element. It allows users to select one or multiple options from a predefined list.

Here’s an example of how to create a list box in HTML:

HTML<span role="button" tabindex="0" data-code="<select> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> <option value="option4">Option 4</option>
<select>
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
  <option value="option4">Option 4</option>
</select>

In the above example, the <select> element defines the list box. Each <option> element represents an individual item within the list. The value attribute specifies the value associated with each option, which is typically used for form submission or JavaScript manipulation. The text within the <option> tags is the visible label that the user sees.

By default, the list box allows users to select only one option at a time. However, if you want to allow multiple selections, you can add the multiple attribute to the <select> element:

HTML<span role="button" tabindex="0" data-code="<select multiple> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> <option value="option4">Option 4</option>
<select multiple>
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
  <option value="option4">Option 4</option>
</select>

In this case, users can select multiple options by holding down the Ctrl (or Command on Mac) key while clicking on the desired options.

You can also set a default selected option by adding the selected attribute to the <option> tag:

HTML<span role="button" tabindex="0" data-code="<select> <option value="option1">Option 1</option> <option value="option2" selected>Option 2</option> <option value="option3">Option 3</option> <option value="option4">Option 4</option>
<select>
  <option value="option1">Option 1</option>
  <option value="option2" selected>Option 2</option>
  <option value="option3">Option 3</option>
  <option value="option4">Option 4</option>
</select>

In this example, “Option 2” will be preselected when the list box is rendered.

To access the selected option(s) from the list box in JavaScript, you can use the selectedIndex and options properties of the <select> element.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS