Set selected option by text of dropdownlist


In this post we will see how to set selected option by text to dropdownlist. In web application we need to set dropdownlist value at client side. By using option property of dropdown list we will check if dropdown contains text that we want to set And after that using selected attribute we will set it true so that it will show the option selected that we have set using text.
set selected option in dropdownlist using jquery

Sample to set selected option by text to dropdownlist[jQuery]


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>Set dropdownlist selected option by text</title>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#go").click(function () {
         var inputText = $("#inputText").val();
          $("#numbers option:contains(" + inputText + ")").attr('selected', 'selected'); 
        });
      });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <label>Enter value between 1-3</label>
      <input type="text" id="inputText"/>
    <asp:DropDownList ID="numbers" runat="server">
    <asp:ListItem Text="1" Value="1"></asp:ListItem>
    <asp:ListItem Text="2" Value="2"></asp:ListItem>
    <asp:ListItem Text="3" Value="3"></asp:ListItem>
    </asp:DropDownList>
    </div>
    <input type="button" id="go" value="Go" />
    </form>
</body>
</html>


Summary:By using $("#numbers option:contains(" + inputText + ")").attr('selected', 'selected'); we have dynamically set the selected option of a drop-down list using JQuery.We can set selected option of dropdown list by it's value likeset selected option of dropdown box by value

2 comments :

  1. This doesn't work if you have multiple options that matches the contains statement. Say you have items "Test" and "Test1". The contains statement will find both items.

    ReplyDelete
    Replies
    1. Yes you are right. :contains will return all matched items that contains same text. But you can do it by iterating through dropdownlist and then compare searching text with each dropdownlist item and then set option selected for dropdown.

      like:
      $("#numbers").each(function () {
      $('option', this).each(function () {
      if ($.trim($(this).text().toLowerCase()) == $.trim(inputText.toLowerCase())) {
      $(this).attr('selected', 'selected');
      };
      });
      });
      Look at example :http://www.codegateway.com/2012/04/jquery-set-dropdownlist-exact-text.html

      Delete