我正在尝试根据下拉菜单中选择的内容更改输入的值,但它总是返回“undefined”。这是HTML:
<select id="dropdown">
<option id="AU">Australia</option>
<option id="CH" >Switzerland</option>
</select>
<input type="text" id="regionInput">
和JS:
document.getElementById('dropdown').setAttribute("onchange","myFunction()");
function myFunction(){
var country = document.getElementById('dropdown').options[document.getElementById('dropdown').selectedIndex].text;
var region = document.getElementById('regionInput').value;
if (country == "Australia"){
region = 'test';
} else {
region = 'test 2';
}
}
任何帮助将不胜感激!
答案 0 :(得分:0)
听起来你正在将函数定义为另一个函数的局部范围。从onXXX
属性调用的代码在全局范围内执行。
您可以使用addEventListener
并提供功能参考:
document.getElementById('dropdown').addEventListener("change",myFunction);
请注意,事件名称不以on
开头,并且您不必将()
放在函数名称后面(将调用函数而不是传递引用)
答案 1 :(得分:-1)
尝试删除myFuction()中的引号""
,如下所示:document.getElementById('dropdown').setAttribute("onchange", myFunction() );