且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何更改Java脚本的下拉列表中的选定文本

更新时间:2023-02-11 19:30:17

subhashyadav.smec@gmail.com写道:
subhashyadav.smec@gmail.com wrote:

其中下拉列表为空白,我只有下拉列表项没有索引

where the drop down is blank and i have only item of dropdown not index



如果下拉列表为空白,那么您想如何选择任何东西,这真的很令人困惑:)



This is really very confusing, if the dropdown is blank how you want to select any thing :)

subhashyadav.smec@gmail.com写道:
subhashyadav.smec@gmail.com wrote:

如何在运行时更改Java脚本下拉列表中的选定文本

how to change selected text in dropdown list in java script at run time





为此,我们举一个例子





For this Let’s take following example

<asp:DropDownList ID="ddlTest" runat="server">
            <asp:ListItem Text="One" Value="1"></asp:ListItem>
            <asp:ListItem Text="Two" Value="2"></asp:ListItem>
            <asp:ListItem Text="Three" Value="3"></asp:ListItem>
        </asp:DropDownList>



如果您知道这种情况下的价值,则可以直接选择下拉菜单,如下所示.



If you know the value in that case your can directely select the drop down like following.

document.getElementById("ddlTest").value = 2;



如果您有文字,并且想要在这种情况下选择下拉列表,则需要按以下方式循环下拉列表.



If you have text and you want to select the dropdown list in that case you need to loop the dropdown list as following.

<script language="javascript">
        function setSelectedIndex(ddl, txt) {
            for (var i = 0; i < ddl.options.length; i++) {
                if (ddl.options[i].text == txt) {
                    ddl.options[i].selected = true;
                    return;
                }
            }
        }
    </script>




您可以将此方法称为follwong.




And you can call this method as follwong.

setSelectedIndex(document.getElementById("ddlTest"), "Two");