I have a HTML select like this:
<select> <option>a</option> <option>b</option> <option>c</option> </select>
and I have a variable named temp
in my JavaScript:
var temp = "a";
Now I want to set the value of the option that is equal to temp as default value for my select.
How can I do it?
The select tag in HTML is used to create a dropdown list of options that can be selected. The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option.
We can change the HTML select element's selected option with JavaScript by setting the value property of the select element object. We have a select drop down with some options and 2 buttons that sets the selected options when clicked. We get the 2 buttons with getElementById .
To select a <select> element, you use the DOM API like getElementById() or querySelector() . How it works: First, select the <button> and <select> elements using the querySelector() method. Then, attach a click event listener to the button and show the selected index using the alert() method when the button is clicked.
You first need to add values to your select
options and for easy targetting give the select
itself an id
.
Let's make option b
the default:
<select id="mySelect"> <option>a</option> <option selected="selected">b</option> <option>c</option> </select>
Now you can change the default selected value with JavaScript like this:
<script> var temp = "a"; var mySelect = document.getElementById('mySelect'); for(var i, j = 0; i = mySelect.options[j]; j++) { if(i.value == temp) { mySelect.selectedIndex = j; break; } } </script>
Also we can use "text" property of i to validate:
if(i.text == temp)
See it in action on codepen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With