How to Populate a Cascading Dropdown with Jquery

How to populate a cascading Dropdown with JQuery

It should as simple as

jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Russia': ['St. Petersburg'],
}

var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];

var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});

Demo: Fiddle

Cascading drop-down lists in C# MVC using jquery

You do not have an <select> element with id="MaterialId". Your @Html.DropDownListFor(model => model.Material.MaterialId, ...) line of code generates a <select> with id="Material_MaterialId"

Nor do you have an element with id="LengthId" - its id="Length_LengthId"

Change you script to

var lengthSelect = $('#Length_LengthId');
$("#Material_MaterialId").change(function () {
var id = $(this).val();
$.get('@Url.Action("GetLengthList", "Drawing")', { MaterialId: id }, function (data) {
lengthSelect.empty();
$.each(data, function (index, row) {
lengthSelect.append("<option value='" + row.LengthId + "'>" + row.LengthValue + "</option>")
});
});
})

I also suggest you study the code in this DotNetFiddle, in particular the controller code to know how to implement this correctly so that it can be used for editing existing items, and allow you to return the view if ModelState is invalid without losing the data the user entered, and to return only the data you need to generate the <option> elements.

Jquery dependent drop down boxes populate- how

var drop2 = $("select[name=drop2] option"); // the collection of initial options
$("select[name=drop1]").change(function(){
var drop1selected = parseInt(this.value); //get drop1 's selected value
$("select[name=drop2]")
.html(drop2) //reset dropdown list
.find('option').filter(function(){
return parseInt(this.value) < drop1selected; //get all option with value < drop1's selected value
}).remove(); // remove
});

http://jsfiddle.net/HTEkw/

create a cascading dropdown list with JavaScript and jQuery

This works as requested, I've commented the change in the code so it should be self explainatory. I've hidden all the options and then shown the ones that match the selection on the first drop down.


DEMO

$(document).ready(function(){
var $cat = $('select[name=category]'),
$items = $('select[name=items]');

$cat.change(function(){

var $this = $(this).find(':selected'),
rel = $this.attr('rel');

// Hide all
$items.find("option").hide();

// Find all matching accessories
// Show all the correct accesories
// Select the first accesory
$set = $items.find('option.' + rel);
$set.show().first().prop('selected', true);

});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Cascading Dropdown Example</h1>
<select name="category">
<option value="0">None</option>
<option value="1" rel="accessories">Cellphones</option>
<option value="2" rel="sports">Sports</option>
<option value="3" rel="cars">Cars</option>
</select>
<select name="items" class="cascade">
<option value="3" class="accessories">Smartphone</option>
<option value="8" class="accessories">Charger</option>
<option value="1" class="sports">Basketball</option>
<option value="4" class="sports">Volleyball</option>
<option value="6" class="cars">Corvette</option>
<option value="2" class="cars">Monte Carloe</option>
</select>

How to create cascading drop-down list

The idea of cascading drop-down is, you select a value in the first drop-down, and it triggers some action to load the options for a second drop-down. A classic example is Country drop-down down and State drop-down. Every time user selects a country the country drop-down should be updated with the states under that country.

I am going to give you a very generic example of the Country-State use case. You can use the same concepts to build your specific use case

To start with , create a view model for your view. Create a property of type List<SelectListItem> for passing the list of options needed for building the SELECT element and another property to store the selected option value. We will do this for both the SELECT elements.

public class CreateUserVm
{
public List<SelectListItem> Countries { set;get;}
public int SelectedCountryId { set;get;}

public List<SelectListItem> States { set;get;}
public int SelectedStateId { set;get;}

public CreateUserVm()
{
this.Countries = new List<SelectListItem>();
this.States = new List<SelectListItem>();
}
}

Now in your GET action method, create an object of this view model, initialize the options for the first dropdown , in this case the Countries property and send that to the view.

public ActionResult Create()
{
var vm=new CreateUserVm();
vm.Countries = GetCountries();
return View(vm);
}
private List<SelectListItem> GetCountries()
{
var list = new List<SelectListItem>
{
new SelectListItem() {Value = "1", Text = "USA"},
new SelectListItem() {Value = "2", Text = "India"},
};
return list;
}

Now in your View, which is strongly typed to our view model. we will use the DropDownListFor helper method to render the drop-downs

@model CreateUserVm
@using (Html.BeginForm("Index", "Home"))
{
@Html.DropDownListFor(a=>a.SelectedCountryId,Model.Countries,"Select one")
@Html.DropDownListFor(a => a.SelectedStateId, Model.States, "Select one",
new { data_url = Url.Action("GetStates") })
<input type="Submit" />
}

This will render 2 dropdowns, one with Country options and the second one will be empty (because we did not load anything to the States property). Now we will have some javascript(we are using jquery here for easy DOM manipulation) which will listen to the change event of the first drop-down(Country) ,read the selected value and make an ajax call to the GetStates method and passing the selected country option value.

You can see that , i set a html5 data attribute for the second dropdown where i am storing the url to the GetStates method. So in my javascript, i can simply read this data attribute value and make a call to that url to get the data.

$(function () {
$("#SelectedCountryId").change(function () {
var v = $(this).val();
var url = $("#SelectedStateId").data("url") + '?countryId=' + v;
var $states = $("#SelectedStateId");
$.getJSON(url, function (states) {
$states.empty();
$.each(states, function (i, item) {
$states.append($("<option>").text(item.Text).val(item.Value));
});
});
});
});

Now, let's add a GetStates action method which accepts the countryId and return the states for that country in a list of SelectListItem as JSON array.

public ActionResult GetStates(int countryId)
{
var states = new List<SelectListItem>();
if (countryId == 1)
{
states.Add(new SelectListItem() {Value = "101", Text = "Michigan"});
states.Add(new SelectListItem() { Value = "102", Text = "New York" });
}
else if (countryId == 2)
{
states.Add(new SelectListItem() { Value = "103", Text = "Kerala" });
states.Add(new SelectListItem() { Value = "104", Text = "Goa" });

}
return Json(states, JsonRequestBehavior.AllowGet);
}

Here i have hard coded the Countries and States. But if you have a database which has this data, replace the hard coded values with data from your tables.

When you are editing a record, All you have to do is, load the States property in the GET action based on the CountryId which is saved.

How to fill cascading dropdownlist each other by using jquery in mvc 3?

For starters, the <script> tag in which you are loading jquery is not properly closed:

<script type="text/javascript" src="../../Scripts/jquery-1.4.4.js">

It should be like this:

<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery-1.4.4.js") %>"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#ddlCustomers').change(function () {
var idColour = $(this).val();
var url = '<%= Url.Action("LoadJobByCustomerId", "Job") %>';
$.getJSON(url, { customerId: idColour }, function (modelData) {
var select = $("#ddlJobs");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a Colour"
}));
$.each(modelData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
});
</script>

<% using (Html.BeginForm()) { %>
<table style="padding:25px; margin:10px 10px 10px 10px;" id="sample">
<tr>
<td>Customer Name: </td>
<td>
<%= Html.DropDownList(
"Customers",
null,
"** Please Select **",
new { id = "ddlCustomers" }
)%>
</td>
</tr>
<tr>
<td>Job Name:</td>
<td>
<%= Html.DropDownList(
"Jobs",
null,
"** Please Select **",
new { id = "ddlJobs" }
)%>
</td>
</tr>
</table>
<% } %>

Also jQuery 1.4.4's kinda old. Maybe you wanna switch to a more recent version.

Another things that I have fixed in your code is the usage of Url helpers instead of hardcoding urls, missing closing }); for the document.ready handler, broken markup with inconsistent opening and closing <tr> and <td> tags, ...

I don't know how are you guys writing/indenting your code, but I would really recommend you putting a little more attention.

And next time when developing a javascript intensive web application and something doesn't work, your immediate reflex should be to look in the FireBug console or Chrome developer toolbar (depending on the web browser you are using) instead of posting on Stack Overflow without any investigation. FireBug would have alerted you on at least 50% of the errors you committed in your code.

Further improvement of this code is to get rid of ViewData by introducing view models and the usage of strongly typed helpers, as I have exemplified in this post: https://stackoverflow.com/a/4459084/29407

Using Ajax to fill a cascading dropdown list

The problem here was in the call.

$.ajax({
type: "POST",
url: "AjaxController/Index",
async: true,
data: "{KovID:" + kovID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",

Both the type and the url were incorrect. I should have been:

$.ajax({
type: "GET",
url: '/Ajax/Index',
async: false,
data: { KovID: kovID },
contentType: "application/json; charset=utf-8",
dataType: "json",

Populating a cascading dropdown on parent dropdown selection using jQuery

Your Category class doesn't seem to have a Value property. In your controller action you are populating only the Id and Name properties, so use them to bind the dropdown:

$.each(childCategories, function(index, childCategory) {
childCategoriesDdl.append(
$('<option/>', {
value: childCategory.Id,
text: childCategory.Name
})
);
});

By the way because you only need an Id and a Name there is no need to send the other properties over the wire and waste bandwidth. Use a view model or in this case an anonymous object would do just fine:

public ActionResult AjaxBindingChildCategories(int parentCategoryId)
{
IEnumerable<Category> childCategoryList = categoryService.GetChildCategoriesByParentCategoryId(parentCategoryId);
var childList =
from c in childCategoryList
select new
{
Id = c.Id,
Name = c.Name
};

return Json(childList, JsonRequestBehavior.AllowGet);
}

Populating using object array and filtering cascade dropdown lists using jQuery

If I understand you correctly, you can iterate over each crop object and check if the crop matches the value of the drop down, and if it does, populate the other two dropdowns accordingly:

$('#crop').append(selectOptions).on('change', function () {
var selected = $(this).find('option:selected').val();
$('#type, #practice').empty();
$.each(crops, function(i, v) {
if (v.Crop == selected) {
$('#type').append('<option value="'+v.Type+'">'+v.Type+'</option>');
$('#practice').append('<option value="'+v.Practice+'">'+v.Practice+'</option>');
}
});
});

Example Fiddle



Related Topics



Leave a reply



Submit