使用Javascript从多个下拉列表中显示多个值

时间:2014-04-29 23:44:41

标签: javascript jquery html

我正在尝试使用Javascript将每个下拉列表中的一个值显示到其对应的文本字段。我已经使用“匹配”文本字段构建了下拉菜单,但似乎无法在多个下拉菜单中显示任何值。

<body>
<select name="DDcabinets" id="DDcabinets">
    <option value="">Select an option …</option>
    <option value="100">Dura Supreme</option>
    <option value="110">Lenape Village</option>
    <option value="120">Wellborn Forest</option>
</select>
<input type="text" name="Vcabinets" id="Vcabinets" size="15" maxlength="5"/>
<br>
<select id="DDcountertop">
    <option value="">Select an option …</option>
    <option value="200">Granite</option>
    <option value="210">Quartz</option>
    <option value="220">Solid Surface</option>
    <option value="230">Laminate</option>
</select>
<input type="text" id="Vcountertop" size="15" maxlength="5"/>
<br>
<select id="DDbacksplash">
    <option value="">Select an option …</option>
    <option value="300">Tile</option>
    <option value="310">Other</option>
</select>
<input type="text" id="Vbacksplash" size="15" maxlength="5"/>

等等。有什么建议吗?

编辑:我的javascript:

var select = document.getElementById('DDcabinets');
var input = document.getElementById('Vcabinets');
select.onchange = function() {
    input.value = select.value;
}

1 个答案:

答案 0 :(得分:0)

您最初可能会将控件ID混淆,但以下代码可以正常工作:

<html>
<head>
<script>
    window.onload = function () {
        var select1 = document.getElementById('DDcabinets');
        var input1 = document.getElementById('Vcabinets');
        select1.onchange = function () {
            input1.value = select1.value;
        };
        var select2 = document.getElementById('DDcountertop');
        var input2 = document.getElementById('Vcountertop');
        select2.onchange = function () {
            input2.value = select2.value;
        };
        var select3 = document.getElementById('DDbacksplash');
        var input3 = document.getElementById('Vbacksplash');
        select3.onchange = function () {
            input3.value = select3.value;
        };
    }
</script>
</head>
<body>
<div>
    <select id="DDcabinets">
        <option value="">Select an option …</option>
        <option value="100">Dura Supreme</option>
        <option value="110">Lenape Village</option>
        <option value="120">Wellborn Forest</option>
    </select>
    <input type="text" id="Vcabinets" size="15" maxlength="5" />
    <br />
    <select id="DDcountertop">
        <option value="">Select an option …</option>
        <option value="200">Granite</option>
        <option value="210">Quartz</option>
        <option value="220">Solid Surface</option>
        <option value="230">Laminate</option>
    </select>
    <input type="text" id="Vcountertop" size="15" maxlength="5" />
    <br />
    <select id="DDbacksplash">
        <option value="">Select an option …</option>
        <option value="300">Tile</option>
        <option value="310">Other</option>
    </select>
    <input type="text" id="Vbacksplash" size="15" maxlength="5" />
</div>
</body>
</html>