The jQuery Mutiselect plugin allows users to select multiple items from the options available in the dropdown. When we click on the dropdown, it looks something like the below :
Check out the demo page of the plugin here.
The problem with the plugin is that it won’t remember the user selection, and value will be lost on postback. You can store the selected value delimited by a comma in the hidden field and restore the value on the page load.
Now let’s look at the code to bind the dropdown with the plugin and retain value on postback.
Make sure you have the necessary scripts and CSS files added to your page:
HTML:
<asp:DropDownList ID="ddlUsers" runat="server" multiple="multiple">
</asp:DropDownList> <asp:HiddenField ID="hdnUsers" runat="server" />
<asp:Button ID="btnSearch" runat="server" Text="Search" onclick="btnSearch_Click" />
Client Script:
$('#').multiselect({
//to remove check/uncheck all option
header: '',
//store user selected value in hidden field
close: function (event, ui) {
var array_of_SalesGroup = $('#').multiselect("getChecked").map(
function () {
return this.value;
}).get();
$('#').val(array_of_SalesGroup);
}
}).multiselectfilter(); //adds filter to dropdown
Now to check checkboxes marked by a user, we need to add the selected attribute to the original select (dropdown) options and call the refresh method of the plugin. You can do it as shown in the below scripts:
$(document).ready(function () {
if ($('#').val() != '') {
var selected = $('#').val().split(",");
$("# > option").each(function () {
if ($.inArray(this.value, selected) > -1) {
$(this).attr("selected", "selected");
}
});
$("#").multiselect('refresh');
}
});
I hope it helps!
Leave a Reply