[NEW] Provenance and Attribution: Minimize IP liability for GenAI output
Home / Blog /
How to Use Option Selected Property in JavaScript
//

How to Use Option Selected Property in JavaScript

//
Tabnine Team /
4 minutes /
December 24, 2020

The <select> element creates a drop-down menu on the rendered output.

You can add options to the drop-down menu by using nested <option> elements. This creates a list for the user to select from.

Retrieving the selected option value can be done using the following code sample:

HTML

<select id="greet">
  <option value="hello">Hello</option>
  <option value="goodbye">Goodbye</option>
  <option value="seeYou">See you...</option>
</select>

JavaScript

console.log(document.getElementById('greet').value);
//Expected output: hello

Syntax

Retrieving the selected value from a <select> element is done using the value attribute

selectElement.value

In the above code, the HTML document has a <select> element. Its id is set to greet, and it has three options to choose from. Each option has a value attribute – this value attribute can be identical to the text, or not – you are free to assign whichever value you prefer.

In the above JavaScript code, the element’s value is passed in as an argument to console.log(). The element is retrieved using the document.getElementById() method, which finds an element in the document with the specified id.

The value attribute returns the value of the currently-displayed option in the drop-down.

However, in the above example the print to the console will only happen once. If the user selects a new option, the new value will not be printed to the log.

There are three common ways to solve this issue:

1. DOM events

The first solution is to use DOM events to call an event handler. Take the following example code:

HTML

<select id="greet" onchange="getOption()">
  <option value="hello">Hello</option>
  <option value="goodbye">Goodbye</option>
  <option value="seeYou">See you...</option>
</select>

The <select> element above uses the onchange DOM event. The onchange event fires whenever a different value is selected from the drop-down list. The event then triggers the getOption() function, which displays the result.

JavaScript

function getOption() {
  console.log(document.getElementById('greet').value);
}

This approach has a problem – namely, if the user does not choose a different value, no change takes place. This means that the function handler is not called unless the value of the drop-down changes. There are other events we can use in place of onchange, but each has its own problems:

The onclick event always returns the first option in the list first, as the user must click on the drop-down menu in order to open the selection list. When a new element is selected, the event handler is called again and the selected value is returned as expected.

The onblur event returns the correct value, but triggers the handler function only as the field loses focus. This can be as a result of the user clicking elsewhere on the page, or using the tab key to move to a different field.

2. Adding a placeholder “title” option

Due to the behavior of event handlers with the select menu, a common solution is to use a placeholder element as the first option. This placeholder element gives a brief prompt about how to use the drop down. Take the following example code:

HTML

<select id="greet" onchange="getOption(this)">
  <option>Pick your greet</option>
  <option value="hello">Hello</option>
  <option value="goodbye">Goodbye</option>
  <option value="seeYou">See you...</option>
</select>

This defines a drop-down menu with the default option being a placeholder that reads “Pick your greet”. Now, a change must occur if the user wishes to select a greeting.

Note: In the above example, it is possible to select “Pick your greet” as an option! Although the first click on the placeholder will not invoke getOption() (because no change was made), it will be possible to select the placeholder after a change was made. The value of this option, by default, will be equal to the text of the option itself – in the above example, the value will be a String containing “Pick your greet”.

We can build on this by adding a convenience value to this default option, then filter it out at the beginning of our getSelection() function. The following example code demonstrates how to do this:

JavaScript

function getOption(el) {
  const option = el.value;
  if (option === 'esc') return
    console.log(option);
  return option;
}

Now, when the option “Pick your greet” is selected, the console.log(option) will not occur.

Note: the default value of an option element is the text which appears between the <option> </option> tags. This is changed by adding a value attribute. If a value attribute is present, it takes precedence over the default value.

3. Using a form

The third option is to use a Form. Forms need to be submitted, and when they are submitted, all values from all inputs can be organized into an Object, which is a common way to store data in JavaScript. You can also store the contents of the form in an Array or String, depending on your application’s requirements. The following sample code demonstrates how to use forms to retrieve the value of drop-down lists on the page:

HTML

<form>
  <select>
    <option value="hello">Hello</option>
    <option value="goodbye">Goodbye</option>
    <option value="SseYou">See you...</option>
  </select>
  <select>
    <option value="Run">Run</option>
    <option value="Done">Done</option>
    <option value="Fun">Fun</option>
  </select>
  <button onclick="submitForm(event)">Submit</button>
</form>

JavaScript

function submitForm(ev) {
  ev.preventDefault();
  let selectInputs = document.querySelectorAll('select');
  let res = [];
  selectInputs.forEach(input => {
   res.push(input.value)
  })
  return res;
}

Forms enable handling many inputs, gathering all of the information only once, when the form is submitted. In the above example, there are two <select> menus in the <form>.

The form above is submitted by clicking on the Submit button, which invokes the submitForm() event handler. This function receives the triggering DOM event as a parameter – in this case, it receives an onclick event.

By default, submitting a form results in a page refresh. This clears all of the data the user has inserted, resetting the form to its default values. The above code prevents this from happening by taking the event received as a parameter and applying the preventDefault() method to it. This prevents the page refresh and subsequent loss of data.

The next line finds all of the <select> elements in the form and declares the resarray to which the data will be inserted. Remember that document.querySelectorAll() returns an array, which is why an iteration method is required – e.g. forEach(). forEach() takes each input element present in the array returned by querySelectorAll, and then pushes its value onto res.

 

Related Articles:

JavaScript – How to Use onfocus

JavaScript – How to Get an Input’s Value

JavaScript – How to Use The Array forEach() Method