如何使用javascript添加“selected”来选择选项

时间:2015-07-10 15:32:24

标签: javascript

我有以下代码,当用户选择一个选项时,我试图动态地将“selected”添加到该选项中。我怎么能用Javascript做到这一点? 用户选择“Candy”时的示例我想添加<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>

2 个答案:

答案 0 :(得分:2)

这应该做:

var select = document.getElementById('BusinessType');
select.addEventListener('change', function() {

  select.options[select.selectedIndex].setAttribute('selected');
});

另外我建议您将id的名称更改为business-type,因为CSS不是用camelCase编写的。

答案 1 :(得分:0)

var select = document.getElementById('BusinessType');
select.options[indexOfoption].selected = true;

您也可以通过此方法进行操作。很容易理解