Reputation: 5406
HI I have a issue with filtering one drop down list with another drop down list, in my search.cshtml file I have added
@{
List<FormCategory> formCategories = ViewBag.formCategories;
List<Form> forms = ViewBag.forms;
List<UsersVM> users = ViewBag.Users;
List<FormSearchResultsVM> results = ViewBag.Results;
}
<select id="selFormCategories" class="sc-select sc-input" onchange="onFormCategoriesChanged(this)">
<option id="0"></option>
@foreach (var formCat in formCategories)
{
<option value="@formCat.ID">@formCat.Name</option>
}
</select>
<select id="selForms" class="sc-select sc-input" onchange="onFormsChanged(this)">
<option id="0"></option>
@foreach (var form in forms)
{
<option value="@form.ID">@form.Name</option>
}
</select>
I need to filter selForms dropdown when selFormCategories onchnage event...
function onFormCategoriesChanged(sel) {
selectedFormCategory = $(sel).find(':selected').attr('value');
}
Thanks
Upvotes: 1
Views: 1386
Reputation: 6140
Here's one way I could think of. First, we should store the option elements to a jquery object array then filter that array for display whenever a select is changed.
Data attributes (data-property, data-name, etc) is used for filtering.
In my example below, whenever the vehicle select is changed, it will clear and refill the brands select with corresponding brands from that vehicle type.
$(document).ready(function(){
var vehicleList = [];
var brandsList = [];
// store brands options to variable on document ready
$("#brands option").each(function(){
brandsList.push($(this));
});
// clear brands select to hide option fields
$("#brands").html("");
// vehicle select on change, refill brands with matching data-vehicle value
$("#vehicle").change(function(){
var brandsSelect = $("#brands");
var vehicleValue = $(this).val();
brandsSelect.html("");
brandsSelect.show();
$(brandsList).each(function(){
if($(this).data("vehicle") == vehicleValue){
$(brandsSelect).append($(this));
}
});
});
});
<html>
<body>
<h5>Select a Vehicle Type</h5>
<select id="vehicle">
<option>Motorcycle</option>
<option>Car</option>
</select>
<h5>Choose Brand</h5>
<select id="brands" hidden>
<option data-vehicle="Motorcycle">Yamaha</option>
<option data-vehicle="Motorcycle">Kawasaki</option>
<option data-vehicle="Car">Mercedes Benz</option>
<option data-vehicle="Car">BMW</option>
<option data-vehicle="Car">Audi</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
Upvotes: 2