jquery set dropdownlist exact text

We have seen how to set selected option in dropdown list by text here set dropdownlist selected option by text. In that example we used :contains selector that will look for the text and the set text in dropdownlist as selected.

dropdownlist set exact selected text
But if dropdownlist have items with same texts instance then :contains selector will get all the items with matched text. This might show last matched item selected in dropdownlist. In this case we need to use alternate way to get exact text in dropdownlist and then set it selected.

Example to set selected option in dropdown by exact text [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 dropdown value</title>
  <script type="text/javascript">
    $(document).ready(function () {
      $("#go").click(function () {
        var inputText = $("#inputText").val();
        $("#numbers").each(function () {
          $('option', this).each(function () {
            if ($.trim($(this).text().toLowerCase()) == $.trim(inputText.toLowerCase())) {
              $(this).attr('selected', 'selected');
            };
          });
         });
       });
    });
 </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <label>Enter value from dropdown</label>
    <input type="text" id="inputText" />
    <asp:DropDownList ID="numbers" runat="server">
      <asp:ListItem Text="This is one" Value="1"></asp:ListItem>
      <asp:ListItem Text="This is one?" Value="2"></asp:ListItem>
      <asp:ListItem Text="This is three" Value="3"></asp:ListItem>
    </asp:DropDownList>
  </div>
  <input type="button" id="go" value="Go" />
  </form>
</body>
</html>

Summary: So by using :contains it might not work for multiple items with istance of same text. But we can iterate through dropdown items and then by matching exact text we can set dropdown list text selected.