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.
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