Vinit Patel

Limited Selection from Listbox

Posted on: February 9, 2010


Hi,

If I want to select only limited(2) items from the listbox then using Jquery use the below code,

<head id=”Head1″ >
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script&gt;

</head>
<body>
<form runat=”server”>
<asp:ListBox ID=”ListBox1″ runat=”server” SelectionMode=”Multiple”>
<asp:ListItem Text=”Item1″></asp:ListItem>
<asp:ListItem Text=”Item2″></asp:ListItem>
<asp:ListItem Text=”Item3″></asp:ListItem>
<asp:ListItem Text=”Item4″></asp:ListItem>
</asp:ListBox>
</form>
</body>
<script type=”text/javascript”>
$(‘#<%= ListBox1.ClientID %>’).change(function()
{
if ($(this).find(‘option:selected’).length > 2)
{
this.options[this.selectedIndex].selected = false;
}
;
});
</script>

</html>

Using Javascript

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head id=”Head1″ >

<script type=”text/javascript”>
function test()
{
var selectedCount = 0;
var listBox = document.getElementById(‘<%= ListBox1.ClientID %>’);
var i = 0;
do
{
if (listBox.options[i].selected)
{
selectedCount++;
if (selectedCount > 2)
{
listBox.options[i].selected = false;
break;
}
}
i++;

} while (i < listBox.options.length)
}
</script>

</head>
<body>
<form runat=”server”>
<asp:ListBox ID=”ListBox1″ runat=”server” onchange=”test()” SelectionMode=”Multiple”>
<asp:ListItem Text=”Item1″></asp:ListItem>
<asp:ListItem Text=”Item2″></asp:ListItem>
<asp:ListItem Text=”Item3″></asp:ListItem>
<asp:ListItem Text=”Item4″></asp:ListItem>
</asp:ListBox>
</form>
</body>
</html>

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Calendar

February 2010
M T W T F S S
« Dec   Apr »
1234567
891011121314
15161718192021
22232425262728

Stats Of Blog

  • 6,848 hits

Cluster Map

%d bloggers like this: