简体   繁体   English

如何使用列表框的一个值来设置另一个列表框的值?

[英]how to use one value of a listbox to set another listbox's value?

I am learning Javascript for the first time. 我是第一次学习Javascript。 I am trying to select one value for listbox1 and based on that value it must select the value in listbox2. 我试图为listbox1选择一个值,并且必须基于该值选择listbox2中的值。

This is what i coded. 这是我编码的。

<html>
<head>
    function choose() {
        if(document.getElementById('City').value===1) {
            document.getElementById('subcity').value ="1";
            document.getElementById('subcity').text ="Adyar, chennai";       
        }
    }
</head>

<body>
    <select name="City" onchange ="choose()" onclick="" id="City" >
        <option value="0">Select City</option>
        <option value="1">Chennai</option>
        <option value="2">Bangalore</option>
    </select>

    <select name="subcity" id="subcity" >
        <option selected="selected" value="0">Select sub area</option>
        <option value="1">Adyar, chennai</option>
        <option value="2">Electronic city, bangalore</option>
    </select>
</body>
</html>

But it didnt seem to change or set the second listbox. 但是它似乎并没有改变或设置第二个列表框。 It still showed me all the options i had inside it. 它仍然向我展示了我所拥有的所有选择。

Can you please tell the correct way of setting values in the listbox2? 您能告诉我在listbox2中设置值的正确方法吗?

You could try using jQuery 您可以尝试使用jQuery

 $('#City').change(function() {
    $('#subcity').val($('#City').val());
 });

Put this on a separate js file and call it from the html: http://jsfiddle.net/Re8Cc/ 将其放在单独的js文件中,然后从html调用它: http : //jsfiddle.net/Re8Cc/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM