Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add "selected" to select option using javascript

Tags:

javascript

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>
like image 327
user244394 Avatar asked Apr 21 '26 03:04

user244394


1 Answers

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.

like image 119
Chrillewoodz Avatar answered Apr 23 '26 07:04

Chrillewoodz