Reputation: 13478
I have the following code and I am trying to add "selected" to the option dynamically, when the user select an option. How can i do it using Javascript ?
Example when the user select "Candy" I want to add <option value="candy" selected>Candy</option>
function urlDirect() {
var businessTypeSelected = document.getElementById("BusinessType").value;
//alert("x " +x);
if (businessTypeSelected != "") {
window.location.href = location.host + businessTypeSelected;
document.getElementById("BusinessType").selectedIndex = document.getElementById("BusinessType").selectedIndex;
} else {
}
}
<span class="custom-dropdown custom-dropdown--blue custom-dropdown--large">
<select id="BusinessType" class="custom-dropdown__select custom-dropdown__select--blue" onChange="urlDirect()">
<option value="default">Select your business type</option>
<option value="auto">Auto </option>
<option value="aero">Aeroplane</option>
<option value="film">Film</option>
<option value="candy">Candy</option>
</select>
</span>
Upvotes: 3
Views: 7003
Reputation: 1
var select = document.getElementById('BusinessType');
select.options[indexOfoption].selected = true;
You can do it by this method too. it's easy to understand
Upvotes: 0
Reputation: 28368
This should do:
var select = document.getElementById('BusinessType');
select.addEventListener('change', function() {
select.options[select.selectedIndex].setAttribute('selected');
});
Also I'd suggest you change the name of the id
to business-type
since CSS isn't written in camelCase.
Upvotes: 5