How to set default selected value in dropdown using javascript
Hello readers, in this article, I'm going to explain how to set default selected value in dropdown using javascript. Basically, I will share some methods by using them you can easily set default value in select option dynamically.
Set default value in HTML select element using value property.
Yeah! we can set a default value of a select element using value property. The example is given below.
Set default value for select element using value property
<select id="element"> <option>option 1</option> <option>option 2</option> <option>option 3</option> <option>option 4</option> </select> <script> document.querySelector('#element').value = "option 2"; </script>Try it Yourself »
Set default value using index number.
We can also set the default value for select element using the index number of the options.
Set default value for select element using index number
<select id="element"> <option>option 1</option> <option>option 2</option> <option>option 3</option> <option>option 4</option> </select> <script> document.getElementById("element").selectedIndex = 2; </script>Try it Yourself »
- Create a select element with four options and an id named element .
- document.getElementById("element") returns a NodeList with the options.
- The index of the NodeList starts from 0
Set default value of select element using setAttribute method.
set default value for select element
<select id="element"> <option>option 1</option> <option>option 2</option> <option>option 3</option> <option>option 4</option> </select> <script> document.getElementById("element")[1].setAttribute('selected','selected'); </script>Try it Yourself »
Conclusion
In this article, I have shared three ways to set the default selected value in a dropdown using JavaScript.
save
listen
AI Answer
How to set default selected value in dropdown using javascript
1
Hello readers, in this article, I'm going to explain how to set default selected val…
asked
Apu
1 answers
2915
Hello readers, in this article, I'm going to explain how to set default selected val…
Answer Link
answered
Apu
Here is an example using plain JavaScript:
https://www.3schools.in/p/embed.html?q=CjxzZWxlY3QgaWQ9Im15U2VsZWN0Ij4KICA8b3B0aW9uIHZhbHVlPSJ2YWx1ZTEiPk9wdGlvbiAxPC9vcHRpb24+CiAgPG9wdGlvbiB2YWx1ZT0idmFsdWUyIiBzZWxlY3RlZD5PcHRpb24gMjwvb3B0aW9uPgogIDxvcHRpb24gdmFsdWU9InZhbHVlMyI+T3B0aW9uIDM8L29wdGlvbj4KPC9zZWxlY3Q+Cgo8c2NyaXB0PgogIC8vIEdldCBhIHJlZmVyZW5jZSB0byB0aGUgc2VsZWN0IGVsZW1lbnQKICBjb25zdCBzZWxlY3QgPSBkb2N1bWVudC5nZXRFbGVtZW50QnlJZCgibXlTZWxlY3QiKTsKICAvLyBTZXQgdGhlIGRlZmF1bHQgc2VsZWN0ZWQgb3B0aW9uCiAgc2VsZWN0Lm9wdGlvbnNbMl0uc2VsZWN0ZWQgPSB0cnVlOwo8L3NjcmlwdD4=
In this example, the second option (value2) will be selected by default because it has the selected attribute set. You can also use JavaScript to set the default selected option by setting the selected property of the option to true.