javascript
  1. javascript-select

JavaScript Select

The select element is used to create a drop-down list in HTML forms. The JavaScript select object represents this element, allowing you to manipulate its properties and values.

Syntax

document.getElementById("select_id").value

Example

<select id="fruit-select">
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
  <option value="orange">Orange</option>
</select>

<button onclick="showSelectedFruit()">Show selected fruit</button>
function showSelectedFruit() {
  const selectElement = document.getElementById('fruit-select')
  const selectedFruit = selectElement.value
  alert("You selected " + selectedFruit)
}

Output

When user clicks on the "Show selected fruit" button, an alert box will be displayed showing the selected fruit.

Explanation

The document.getElementById("select_id") method is used to get the select element in JavaScript. The value property of the select element object is used to get the selected value in the drop-down list.

In the example code, we have defined a select element with three options: Apple, Banana and Orange. When the user selects an option and clicks on the "Show selected fruit" button, the showSelectedFruit function is called. This function gets the selected value from the select element and displays it in an alert box.

Use

The select object is commonly used in forms to allow the user to pick one or more values from a list.

In JavaScript, you can use the select object to manipulate the options in a select element, such as adding or removing options on the fly based on user input.

Important Points

  • The value property of the select element object is used to get the selected value.
  • The selectedIndex property of the select element object is used to get the index of the selected option.
  • The options property of the select element object is used to get a collection of all the options in the select element.

Summary

The select object in JavaScript represents a drop-down list in an HTML form. It allows you to manipulate the properties and values of the options in the list, and retrieve the selected value. You can use the select object to add or remove options dynamically, based on user input.

Published on: