我正在尝试通过下拉菜单更改文本框,但似乎遇到了问题。
<head>
<title>DropDown</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 0.20" />
<script type="text/javascript">
function chkind() {
var dropdown1 = document.getElementById('dropdown1');
var textbox = document.getElementById('textbox');
var a = dropdown1.options[dropdown1.selectedIndex];
if(a == 0){
textbox.value = "hi";
} else if(a == 1) {
textbox.value = "bye";
}
}
</script>
</head>
<body>
<select onchange="chkind()" id="dropdown1">
<option>Hi</option>
<option>Bye</option>
</select><br />
<input id="textbox" type="text" />
</body>
答案 0 :(得分:10)
可能只是:
var a = dropdown1.selectedIndex;
如果您正在尝试检查是否已选择第0个选项。
或者,或者在HTML中提供您的选项值并自己检查值。
答案 1 :(得分:2)
您需要选择value属性,如下所示:
var a = dropdown1.options[dropdown1.selectedIndex].value;
答案 2 :(得分:1)
我建议你这样做:
<head>
<title>DropDown</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 0.20" />
<script type="text/javascript">
function chkind(){
var dropdown1 = document.getElementById('dropdown1');
var textbox = document.getElementById('textbox');
textbox.value=dropdown1.value;
}
</script>
</head>
<body>
<select onchange="chkind()" id="dropdown1"><option value='Hi'>Hi</option><option value = 'Bye'>Bye</option></select><br /><input id="textbox" type="text" />
</body>
对代码的更改:
<option value='US'>United Stated</option>
。答案 3 :(得分:1)
这应该有效。请注意,'a'是DOM元素(选项)
function chkind(){
var dropdown1 = document.getElementById('dropdown1');
var textbox = document.getElementById('textbox');
var a = dropdown1.options[dropdown1.selectedIndex];
if(a.index == 0){
textbox.value = "hi";
} else if(a.index == 1) {
textbox.value = "bye";
}
}
或
function chkind(){
var dropdown1 = document.getElementById('dropdown1');
var textbox = document.getElementById('textbox');
if(dropdown1.selectedIndex == 0){
textbox.value = "hi";
} else if(dropdown1.selectedIndex == 1) {
textbox.value = "bye";
}
}
答案 4 :(得分:0)
var a = dropdown1.selectedIndex;
if(a == 0){
textbox.value = "hi";
} else if(a == 1) {
textbox.value = "bye";
}
}
答案 5 :(得分:0)
您将所选项目的值存储在变量a
中,因此无法与其索引进行比较。请参阅下面的更正版本。
function chkind(){
var dropdown1 = document.getElementById('dropdown1');
var textbox = document.getElementById('textbox');
var a = dropdown1.selectedIndex;
if(a == 0){
textbox.text = "hi";
} else if(a == 1) {
textbox.value = "bye";
}
}
答案 6 :(得分:0)
$('#selectid option:nth-child(1)').attr('selected', 'selected');