如何添加“选择”使用javascript选择选项
问题描述:
我有以下代码,我试图添加“选择”动态选项,当用户选择一个选项。我怎样才能使用Javascript? 例如当用户选择 “糖果” 我想补充<option value="candy" selected>Candy</option>
如何添加“选择”使用javascript选择选项
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>
答
这应该这样做:
var select = document.getElementById('BusinessType');
select.addEventListener('change', function() {
select.options[select.selectedIndex].setAttribute('selected');
});
而且我建议你改变id
的名字至business-type
,因为CSS没有写在camelCase中。
+0
它将如何记住用户选择的内容?因为每个页面都有相同的下拉/组合框? – user244394
+0
这是另一个问题。我的回答是针对您提供的问题。 – Chrillewoodz
[可能的重复](http://stackoverflow.com/questions/4590311/set-option-selected-attribute-from-dynamic-created-option) – ODelibalta