我的最终目标是制作一个也允许用户输入的下拉菜单。我似乎能做的最好的事情就是在下拉列表旁边添加一个文本框,使其看起来相似,我遇到的问题是,每当我的下拉值发生更改时,我都需要更新文本框。我有一些我一直在玩的代码(如下),但它似乎并没有让我有任何收获!关于如何让它工作的任何指示,或者我是否搞乱了语法? (对于 jscript 和 html 来说都是相当新的)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<style type="text/css">
select
{
width:200px;
}
</style>
<head>
<title>Test</title>
<script type="text/JavaScript">
var select = document.getElementById('theItems');
var input = document.getElementById('stroke');
function otherSelect()
{
input.value = select.value;
}
</script>
</head>
<body>
<form action="" method="">
<input name="stroke"/>
<select name="theItems" onchange="otherSelect()">
<option value="item1">Item One</option>
<option value="item2">Item Two</option>
<option value="item3">Item Three</option>
<option value="item3">Item Four</option>
<option value="other">Other</option>
</select>
<div id="otherBox" style="visibility: hidden;">
If other: <input name="otherField" type="text" />
</div>
</form>
</body>
最佳答案
您应该在 window.onload
事件中执行脚本。当脚本执行时,这些元素不可用于您的脚本。将您的脚本更改为这样
<script type="text/JavaScript">
window.onload = function(){
var select = document.getElementById('theItems');
var input = document.getElementById('stroke');
function otherSelect()
{
input.value = select.value;
}
}
</script>
这样,脚本将在浏览器呈现 HTML 元素后执行。
关于javascript - 在 ValueChange 事件上使用组合框值更新文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17930307/