In this article I will explain how to remove (delete) multiple selected items from the ASP.Net ListBox using JavaScript and jQuery.
Remove (Delete) multiple selected items from ASP.Net ListBox using JavaScript
The following HTML Markup consists of an ASP.Net ListBox control and a Button.
When the Button is clicked, the DeleteValues JavaScript function is executed. Inside this function, a reverse loop is executed over the ListBox items and the selected items of the ASP.Net ListBox control are removed (deleted).
<asp:ListBox ID="ListBox1" runat="server" Width="150" Height="60" SelectionMode="Multiple">
<asp:ListItem Text="Mango" Value="1"></asp:ListItem>
<asp:ListItem Text="Apple" Value="2"></asp:ListItem>
<asp:ListItem Text="Banana" Value="3"></asp:ListItem>
<asp:ListItem Text="Guava" Value="4"></asp:ListItem>
<asp:ListItem Text="Pineapple" Value="5"></asp:ListItem>
<asp:ListItem Text="Papaya" Value="6"></asp:ListItem>
<asp:ListItem Text="Grapes" Value="7"></asp:ListItem>
</asp:ListBox>
<br />
<hr />
<asp:Button ID="btnDelete" Text="Delete" runat="server" OnClientClick="return DeleteValues()" />
<script type="text/javascript">
function DeleteValues() {
var listBox = document.getElementById("<%= ListBox1.ClientID%>");
for (var i = listBox.options.length - 1; i >= 0; i--) {
if (listBox.options[i].selected) {
listBox.removeChild(listBox.options[i]);
}
}
return false;
}
</script>
Remove (Delete) multiple selected items from ASP.Net ListBox using jQuery
The following HTML Markup consists of an ASP.Net ListBox control and a Button.
When the Button is clicked, the jQuery click event handler is executed. Inside this event handler, all the selected options of ASP.Net ListBox control are removed (deleted).
<asp:ListBox ID="ListBox1" runat="server" Width="150" Height="60" SelectionMode="Multiple">
<asp:ListItem Text="Mango" Value="1"></asp:ListItem>
<asp:ListItem Text="Apple" Value="2"></asp:ListItem>
<asp:ListItem Text="Banana" Value="3"></asp:ListItem>
<asp:ListItem Text="Guava" Value="4"></asp:ListItem>
<asp:ListItem Text="Pineapple" Value="5"></asp:ListItem>
<asp:ListItem Text="Papaya" Value="6"></asp:ListItem>
<asp:ListItem Text="Grapes" Value="7"></asp:ListItem>
</asp:ListBox>
<br />
<hr />
<asp:Button ID="btnDelete" Text="Delete" runat="server"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=btnDelete]").bind("click", function () {
$("[id*=ListBox1] option:selected").remove();
return false;
});
});
</script>
Screenshot
Demo
Downloads