Click here to Skip to main content
15,919,132 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to change selected text in dropdown list in java script at run time where the drop down is blank and i have only item of dropdown not index
Posted

1 solution

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 wrote:
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>



And you can call this method as follwong.

setSelectedIndex(document.getElementById("ddlTest"), "Two");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900