This question already has answers here:
Dynamically access object property using variable
                            
                                (14个回答)
                            
                    
                去年关闭。
        

    

我试图从选择中获取一个值,如果选择不正确,则会出现错误。例如:

<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语句吗?

最佳答案

使用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>

关于javascript - 如何在javascript中获得select的值(value)? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56049021/

10-11 12:06