3

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>

1

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

how will it remember what the user has selected? as each page will have the same drop down /combo box?
That's for another question. My answer is for the question you have provided.
0
var select = document.getElementById('BusinessType');
select.options[indexOfoption].selected = true;

You can do it by this method too. it's easy to understand

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.