JQuery to locate items by value or by text in combobox

Here is code snippet to locate items by value or by text in  combobox.

<html>
<head id=”Head1″ runat=”server”>
<script src=”Scripts/jquery-2.0.3.js”></script> <title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:DropDownList ID=”ListBox1″ runat=”server”>
<asp:ListItem Value=”1″>One</asp:ListItem>
<asp:ListItem Value=”2″>Two</asp:ListItem>
<asp:ListItem Value=”3″>Third</asp:ListItem>
<asp:ListItem Value=”4″>Four</asp:ListItem>
<asp:ListItem Value=”5″>Five</asp:ListItem>
</asp:DropDownList>
<br />
<asp:TextBox ID=”text1″ runat=”server”></asp:TextBox><input id=”Button1″ type=”button” value=”By Value” /><input id=”Button2″ type=”button” value=”By Text” /><input id=”Button3″ type=”button” value=”By Text 1″ />
</div>
</form>
</body>
</html>

<script type=”text/javascript”>
//$(‘#ListBox1’).click(function () {
// //$(“input#text1”).val($(“#ListBox1 option:selected”).val());
// alert($(“input#text1”).val == $(“#ListBox1 option:selected”).val());
//});
$(‘#Button1’).click(function () {
var valToSelect=$(“input#text1”).val();
$(“#ListBox1 option[value='” + valToSelect + “‘]”).attr(“selected”, “true”);
//alert($(“input#text1”).val == $(“#ListBox1 option:selected”).val());
alert(valToSelect);
});
$(‘#Button2’).click(function () {
var valToSelect = $(“input#text1”).val();
$(“#ListBox1 option:selected”).text(valToSelect);
alert(valToSelect);
});

$(‘#Button3’).click(function () {
var valToSelect = $(“input#text1”).val();
$(“#ListBox1 option”).each(function () {
if ($(this).text() == valToSelect) {
$(this).attr(‘selected’, ‘selected’);
}
});
});
</script>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.