- 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
- How to Programmatically Select an Option using JavaScript?
- 1. Using the value Property of the Dropdown
- 2. Using the selected Attribute of the Dropdown
- 3. Using the selectedIndex Property
- Conclusion
- Related posts:
- Select an option using javascript
- События элемента select
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
How to Programmatically Select an Option using JavaScript?
A select dropdown is commonly used inside forms that allows users to select an option from a predefined set of options.
But in some cases, we need to select the option from the dropdown dynamically based on some condition. For example, the user is on the edit page and you want to prepopulate the select dropdown with the option that the user previously selected.
In JavaScript, there are different ways to select an option programmatically. Let’s discuss each method one by one.
1. Using the value Property of the Dropdown
The simplest way to select an option from a dropdown in JavaScript is to use the value property of the dropdown element.
In this method, you have to simply set the value property of the dropdown to the value of the option that you want to make auto-selected.
Let me show you this with an example.
Let’s say we have the following select dropdown in our HTML file with some We also have a button which we will use to change the select option dynamically.
We want to make the third option selected using JavaScript.
For that, we will set the value property of the dropdown to the value of the third option:
let dropDown = document.getElementById('myDropdown'); let button = document.getElementById('myBtn'); // Fires on button click button.addEventListener('click', function(event)< // Make third option selected dropDown.value = 'option3'; >);
After running the above code, you will get the following output:
As you can see from the above output, as soon as we click the ‘change’ button, it makes the third option of the dropdown selected.
2. Using the selected Attribute of the Dropdown
You can also use the selected attribute of the dropdown to make an option selected dynamically.
The selected attribute specifies which option of the dropdown should be pre-selected. By default, this attribute is added to the first option, therefore, it remains selected initially.
So, if we want to make any dropdown option selected, we can add the selected=»selected» attribute to it.
See the following example(considering the first example’s HTML code):
let dropDown = document.getElementById('myDropdown'); let button = document.getElementById('myBtn'); // Fires on button click button.addEventListener('click', function(event)< // Make third option selected dropDown.options[2].selected = "selected"; >);
3. Using the selectedIndex Property
The selectedIndex property represents the index of the currently selected option. By default, this property is set to 0, which represents that the first option will be selected initially.
So, if you want to select an option dynamically, you can set the selectedIndex property to the index of the option in the dropdown. Remember that the index starts at 0.
To make the third option selected, you can simply set the selectedIndex to 2:
let dropDown = document.getElementById('myDropdown'); let button = document.getElementById('myBtn'); // Fires on button click button.addEventListener('click', function(event)< // Make third option selected dropDown.selectedIndex = 2; >);
Conclusion
In this article, we learned different ways to make an option selected using JavaScript.
There are actually 3 common ways that you can use to make an option selected using JavaScript. First, using the value property, second, using the selected attribute, and third, using the selectedIndex property of the dropdown.
Based on the data you have, you can choose any of the three methods to make the option selected.
Related posts:
Select an option using javascript
Для создания списка используется html-элемент select. Причем с его помощью можно создавать как выпадающие списки, так и обычные с ординарным или множественным выбором. Например, стандартный список:
Атрибут size позволяет установить, сколько элементов будут отображаться одномоментно в списке. Значение size=»1″ отображает только один элемент списка, а сам список становится выпадающим. Если установить у элемента select атрибут multiple , то в списке можно выбрать сразу несколько значений.
Каждый элемент списка представлен html-элементом option, у которого есть отображаемая метка и есть значения в виде атрибута value .
В JavaScript элементу select соответствует объект HTMLSelectElement , а элементу option — объект HtmlOptionElement или просто Option .
Все элементы списка в javascript доступны через коллекцию options . А каждый объект HtmlOptionElement имеет свойства: index (индекс в коллекции options), text (отображаемый текст) и value (значение элемента). Например, получим первый элемент списка и выведем о нем через его свойства всю информацию:
В javascript мы можем не только получать элементы, но и динамически управлять списком. Например, применим добавление и удаление объектов списка:
Для добавления на форме предназначены два текстовых поля (для текстовой метки и значения элемента option) и кнопка. Для удаления выделенного элемента предназначена еще одна кнопка.
За добавление в коде javascript отвечает функция addOption , в которой получаем введенные в текстовые поля значения, создаем новый объект Option и добавляем его в массив options объекта списка.
За удаление отвечает функция removeOption , в которой просто получаем индекс выделенного элемента с помощью свойства selectedIndex и в коллекции options приравниваем по этому индексу значение null.
Для добавления/удаления также в качестве альтернативы можно использовать методы элемента select:
// вместо вызова // languagesSelect.options[languagesSelect.options.length]=newOption; // использовать для добавления вызов метода add languagesSelect.add(newOption); // вместо вызова // languagesSelect.options[selectedIndex] = null; // использовать для удаления метод remove languagesSelect.remove(selectedIndex);
События элемента select
Элемент select поддерживает три события: blur (потеря фокуса), focus (получение фокуса) и change (изменение выделенного элемента в списке). Рассмотрим применение события select: