![](/img/trans.png)
[英]how to set selectedindex of select2 dropdown in javascript
[英]HTML JavaScript Dropdown selectedIndex
我试图让下拉菜单更改文本框,但似乎有问题。
<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>
可能只是:
var a = dropdown1.selectedIndex;
如果您尝试检查是否选择了第零个选项。
要么,要么在 HTML 中给出您的选项值,然后自己检查这些值。
您需要 select 的 value 属性如下:
var a = dropdown1.options[dropdown1.selectedIndex].value;
我建议你这样做:
<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>
.这应该有效。 请注意,'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";
}
}
$('#selectid option:nth-child(1)').attr('selected', 'selected');
var a = dropdown1.selectedIndex;
if(a == 0){
textbox.value = "hi";
} else if(a == 1) {
textbox.value = "bye";
}
}
您将所选项目的值存储在变量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";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.