- HTMLElement: change event
- Syntax
- Event type
- Examples
- element
- HTML
- JavaScript
- Result
- Text input element
- HTML
- JavaScript
- Result
- Specifications
- Browser compatibility
- Found a content problem with this page?
- Change Option Using JavaScript [With Examples]
- 1. Change Select Option by Value
- 2. Change Select Option by Text
- 3. Change Select Option by Option ID, CLASS, or attribute
- 4. Change Selected Option by its Index
- Conclusion
- Related articles
- Html select change selected javascript
- # Set the Value of a Select Element using JavaScript
- # Removing the selection
- # Getting an array of the values of all option elements
- # Changing the value of a select element
- # Additional Resources
HTMLElement: change event
The change event is fired for , , and elements when the user modifies the element’s value. Unlike the input event, the change event is not necessarily fired for each alteration to an element’s value .
Depending on the kind of element being changed and the way the user interacts with the element, the change event fires at a different moment:
Syntax
Use the event name in methods like addEventListener() , or set an event handler property.
addEventListener("change", (event) => >); onchange = (event) => >;
Event type
Examples
element
HTML
label> Choose an ice cream flavor: select class="ice-cream" name="ice-cream"> option value="">Select One …option> option value="chocolate">Chocolateoption> option value="sardine">Sardineoption> option value="vanilla">Vanillaoption> select> label> div class="result">div>
body display: grid; grid-template-areas: "select result"; > select grid-area: select; > .result grid-area: result; >
JavaScript
const selectElement = document.querySelector(".ice-cream"); const result = document.querySelector(".result"); selectElement.addEventListener("change", (event) => result.textContent = `You like $event.target.value>`; >);
Result
Text input element
For some elements, including , the change event doesn’t fire until the control loses focus. Try entering something into the field below, and then click somewhere else to trigger the event.
HTML
input placeholder="Enter some text" name="name" /> p id="log">p>
JavaScript
const input = document.querySelector("input"); const log = document.getElementById("log"); input.addEventListener("change", updateValue); function updateValue(e) log.textContent = e.target.value; >
Result
Specifications
Browser compatibility
BCD tables only load in the browser
Different browsers do not always agree whether a change event should be fired for certain types of interaction. For example, keyboard navigation in elements used to never fire a change event in Gecko until the user hit Enter or switched the focus away from the (see Firefox bug 126379). Since Firefox 63 (Quantum), this behavior is consistent between all major browsers, however.
Found a content problem with this page?
This page was last modified on Apr 24, 2023 by MDN contributors.
Your blueprint for a better internet.
Change Option Using JavaScript [With Examples]
There are multiple ways you can do it and choosing one or another will depend on the information you have available.
Let’s see 6 different ways of changing the selected option using JavaScript:
1. Change Select Option by Value
To change the selected option programmatically by the value attribute, all we have to do is change the value property of the element.
The select box will then update itself to reflect the state of this property. This is the most straightforward way of updating a select box state.
Let’s say that we want to select the option containing the attribute value=»steve» .
select id="my-select">
option value="ann">Ann Frankoption>
option value="paul" selected>Paul Allenoption>
option value="steve">Steve Jobsoption>
select>
All we have to do is set the value of the select box to that same value:
const changeSelected = (e) =>
const $select = document.querySelector('#mySelect');
$select.value = 'steve'
>;
2. Change Select Option by Text
We might also want to change the value of a select box by the text of the element that gets displayed to visitors.
Doing this is probably the most complicated way, but still, something relatively simple to do. We have to iterate over the options and compare their text with the text of the element we want to select.
Once we find the element we want to update, we’ll be updating its selected property and setting it to true . This way, the select box will also update itself to reflect this change.
Note: this only works for select box elements that only admit a single value. If you are using a select box admiting multiple selected elements this will just add another option to the multi-select instead of changing the active one for another.
const changeSelected = (e) =>
const text = 'Steve Jobs';
const $select = document.querySelector('#mySelect');
const $options = Array.from($select.options);
const optionToSelect = $options.find(item => item.text ===text);
optionToSelect.selected = true;
>;
There’s another way of doing this and that will solve the problem with multi-select inputs. Basically, once we find the element that has the text we are looking for, instead of just changing its selected property, we’ll be getting its value attribute and using it to set it as the only value for the whole select box.
const changeSelected = (e) =>
const text = 'Steve Jobs';
const $select = document.querySelector('#mySelect');
const $options = Array.from($select.options);
const optionToSelect = $options.find(item => item.text ===text);
// Here's the trick:
$select.value = optionToSelect.value;
>;
3. Change Select Option by Option ID, CLASS, or attribute
This is quite simple too. This solution will also work for multi-select inputs by assigning a single value to them:
const changeSelected = (e) =>
const $select = document.querySelector('#mySelect');
const $option = $select.querySelector('#myId');
$select.value = $option.value;
>;
And of course, it can be done in the same way if we have a class attribute instead of an id or any other attribute like data-selected=»true» . Just change the query to get the option element:
// Using id
const $option = $select.querySelector('#myId');
// Using classname
const $option = $select.querySelector('#mySelect .myId');
// Using data-attribute
const $option = $select.querySelector('#mySelect [data-selected="myElement"]');
4. Change Selected Option by its Index
If all we have is the index of the option element, we can set the selected attribute by retrieving the select box options. Then we only have to select the one we need from the array by its index.
Notice that the index is 0-based. So, the first element will have index 0 , the next 1 , and so forth.
Knowing this, if we want to select the 3rd element, we’ll be using index 2 in our code to select it:
// Selecting the 3rd option (Demo 2)
document.querySelector('#mySelect').querySelector('option')[2].selected = 'selected'
Let’s see it working on a click event:
And rewritten to work for multi-select inputs:
// Selecting the 3rd option (Demo 2)
const $select = document.querySelector('#mySelect');
$select.value = $select.querySelector('option')[2].value;
Conclusion
Remember that, no matter what way you choose to use to replace and change the selected element on your elements, you’d be better off updating the value property if you want a single element to be selected. Otherwise, when having select boxes admitting multiple elements you won’t replace the active element but just add another one.
Now you know how to set the value of a element dynamically with JavaScript!
If you are learning JavaScript and this seems a bit difficult for you, there’s nothing to worry about! Eventually, you’ll get there. See how long does it take to learn JavaScript and what’s the best way to learn JavaScript!
Related articles
Html select change selected javascript
Last updated: Jan 11, 2023
Reading time · 3 min
# Set the Value of a Select Element using JavaScript
Use the value property to set the value of a select element, e.g. select.value = ‘new value’ .
The value property can be used to set or update the value of a select element. To remove the selection, set the value to an empty string.
Here is the HTML for the examples.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body style="margin-top: 60px; margin-left: 100px"> select name="fruits" id="fruit-select"> option value="">--Choose an option--option> option value="apple">Appleoption> option value="banana">Bananaoption> option value="kiwi">Kiwioption> select> button style="margin-top: 10px" id="btn">Clickbutton> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!const select = document.getElementById('fruit-select'); // ✅ set select value select.value = 'apple'; console.log(select.value); // 👉️ "apple" // ✅ unset select value // select.value = ''; // -------------------------------- const allOptions = Array.from(select.options).map(option => option.value); console.log(allOptions); // 👉️ ['', 'apple', 'banana', 'kiwi'] // -------------------------------- // ✅ get select value on change select.addEventListener('change', function handleChange(event) console.log(event.target.value); // 👉️ get selected VALUE >); // -------------------------------- // ✅ Set select element value on button click const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() select.value = 'banana'; >);
We used the value property to set the value of a select element.
A convention for when you don’t have a default value is to have the value of the first option element be an empty string.
# Removing the selection
To remove the selection, set the value property of the select element to an empty string.
Copied!const select = document.getElementById('fruit-select'); // ✅ set select value select.value = 'apple'; console.log(select.value); // 👉️ "apple" // ✅ unset select value select.value = '';
# Getting an array of the values of all option elements
If you need an array of the values of all the option elements, use the map() method to iterate over the elements and return the value of each option .
Copied!const select = document.getElementById('fruit-select'); // ✅ set select value select.value = 'apple'; console.log(select.value); // 👉️ "apple" const allOptions = Array.from(select.options).map(option => option.value); console.log(allOptions); // 👉️ ['', 'apple', 'banana', 'kiwi']
# Changing the value of a select element
The value of a select element can be changed in the same way it is set, just update the value property.
Copied!const select = document.getElementById('fruit-select'); select.value = 'apple'; console.log(select.value); // 👉️ "apple" select.value = 'banana'; console.log(select.value); // 👉️ "banana"
If you set a select element’s value to a value that is not present among the option elements, the value of the select element gets reset.
Copied!const select = document.getElementById('fruit-select'); select.value = 'does-not-exist'; console.log(select.value); // 👉️ ""
You can create an object that stores the values of the option elements to avoid misspelling values.
Copied!const select = document.getElementById('fruit-select'); const values = apple: 'apple', banana: 'banana', kiwi: 'kiwi', >; select.value = values.apple; console.log(select.value); // 👉️ "apple" select.value = values.banana; console.log(select.value); // 👉️ "banana"
This is a much better solution than hard-coding strings all over the place because it leverages your IDE’s autocompletion.
It also helps the readers of your code know what the alternative values of the select element are.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.