Reputation: 960
I want to select multiple items in ListBox
, but the browser requires the user to press CTRL to select multiple items otherwise it selects just one item.
I want to select multiple items without pressing CTRL, and I don't want to use CheckBoxList
. Is there any better way of doing it? Using pure javascript, or JQuery or Codebehind.
(I already added SelectionMode="Multiple"
attributes to ListBox
controls)
Code:
<asp:ListBox ID="ListBox1" runat="server" Height="210px" Width="203px" SelectionMode="Multiple">
<asp:ListItem>1000</asp:ListItem>
<asp:ListItem>2000</asp:ListItem>
<asp:ListItem>4000</asp:ListItem>
<asp:ListItem>4000</asp:ListItem>
<asp:ListItem>5000</asp:ListItem>
<asp:ListItem>6000</asp:ListItem>
</asp:ListBox>
Upvotes: 2
Views: 4147
Reputation: 81
If you are using jquery, simply add this script:
$('option').mousedown(function(e) {
e.preventDefault();
$(this).prop('selected', !$(this).prop('selected'));
return false;
});
Upvotes: 0
Reputation: 10030
Ref: Making a standard ASP.NET listbox do multiselect without holding Ctrl
Just change your listbox to
<asp:ListBox ID="ListBox1" runat="server" Height="210px" Width="203px" SelectionMode="Multiple" onclick="ListBoxClient_SelectionChanged(this, event);">
<asp:ListItem>1000</asp:ListItem>
<asp:ListItem>2000</asp:ListItem>
<asp:ListItem>4000</asp:ListItem>
<asp:ListItem>4000</asp:ListItem>
<asp:ListItem>5000</asp:ListItem>
<asp:ListItem>6000</asp:ListItem>
</asp:ListBox>
And add following script in your <script>
tag
<script type="text/javascript" language="javascript">
var selectedClientPermissions = [];
function pageLoad() {
var ListBox1 = document.getElementById("<%= ListBox1.ClientID %>");
for (var i = 0; i < ListBox1.length; i++) {
selectedClientPermissions[i] = ListBox1.options[i].selected;
}
}
function ListBoxClient_SelectionChanged(sender, args) {
var scrollPosition = sender.scrollTop;
for (var i = 0; i < sender.length; i++) {
if (sender.options[i].selected) selectedClientPermissions[i] = !selectedClientPermissions[i];
sender.options[i].selected = selectedClientPermissions[i] === true;
}
sender.scrollTop = scrollPosition;
}
</script>
Upvotes: 5