To create multiple drop-downs where the user can type in the value, you can create multiple select
elements and apply the same Select2 logic to all of them. In this example, I'll create two drop-downs with the same behavior.
- First, update your view to include multiple
select
elements:
@model TestMVC.Models.Customer
@{
ViewData["Title"] = "CustomIndex";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>CustomIndex</h1>
<form method="post" asp-controller="Home" asp-action="CustomIndex">
<select id="ddlCustomers1" name="Name1" asp-items="ViewBag.Select">
<option value="0">--Select Customer 1--</option>
</select>
<br />
<br />
<select id="ddlCustomers2" name="Name2" asp-items="ViewBag.Select">
<option value="0">--Select Customer 2--</option>
</select>
<br />
<br />
<input type="submit" value="Submit" />
</form>
- Next, update the JavaScript code to apply Select2 to both drop-downs. You can use a class or loop through all the elements with a specific id pattern. In this example, I'll use a class called
ddlCustomers
.
<script>
$(function () {
$(".ddlCustomers").select2({
tags: true,
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
},
templateResult: function (data) {
var $result = $("<span></span>");
$result.text(data.text);
if (data.newOption) {
$result.append(" <em>(new)</em>");
}
return $result;
}
});
});
</script>
- Add the
ddlCustomers
class to bothselect
elements in the view:
<select id="ddlCustomers1" name="Name1" class="ddlCustomers" asp-items="ViewBag.Select">
<option value="0">--Select Customer 1--</option>
</select>
...
<select id="ddlCustomers2" name="Name2" class="ddlCustomers" asp-items="ViewBag.Select">
<option value="0">--Select Customer 2--</option>
</select>
Now you have two drop-downs on the same page where users can type in the value inside the drop-down. You can create more drop-downs by adding more select
elements with the ddlCustomers
class and updating the name
attribute accordingly.