javascript - 在 ValueChange 事件上使用组合框值更新文本框

标签 javascript html

我的最终目标是制作一个也允许用户输入的下拉菜单。我似乎能做的最好的事情就是在下拉列表旁边添加一个文本框,使其看起来相似,我遇到的问题是,每当我的下拉值发生更改时,我都需要更新文本框。我有一些我一直在玩的代码(如下),但它似乎并没有让我有任何收获!关于如何让它工作的任何指示,或者我是否搞乱了语法? (对于 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/

相关文章:

javascript - 如何查找 SoundCloud 的轨道信息和 client_id

javascript - 循环创建变量,函数/数组循环

jQuery 获取所有 HTML 属性

javascript - API 输入验证和避免 Big If 语句

javascript - JavaScript 中的 getJSON

html - Magento Foreach 子类别获取产品列表

html - Flexbox 文本和跨度单元格未按预期运行

html - 100% 宽度的 Textarea 溢出父容器

javascript - jQuery 仅在鼠标未按住一定时间(以毫秒为单位)时才运行函数

javascript - 只有 Firefox 类型错误 : "NetworkError when attempting to fetch resource."