我正在尝试从选择中获取值,如果选择不正确,则会出现错误。例如:
<select name = "dogs" id = "dogs">
<option value="dog1">Dog 1</option>
<option value="dog2">Dog 2</option>
<option value="cat1">Cat 1</option>
</select>
如果有人选择了cat1,他们会得到一个错误。
var x = document.getElementById("dogs");
var dogInspector = x.options[x.selectedIndex].value;
if(document.forms['form1'].dogInspector.value === "cat1"){
document.getElementById("validate").innerHTML = "No cats allowed!";
return false;
}
我不确定为什么这行不通?是if语句吗?
答案 0 :(得分:1)
使用x.value
:
var x = document.getElementById("dogs");
x.addEventListener('change', (evt) => {
if(x.value === "cat1"){
alert("No cats allowed!");
}
});
<select name="dogs" id="dogs">
<option value="dog1">Dog 1</option>
<option value="dog2">Dog 2</option>
<option value="cat1">Cat 1</option>
</select>