What's the Best and Easiest Way to Populate a Dropdown Based on Another Dropdown

Populate one dropdown based on selection in another

function configureDropDownLists(ddl1, ddl2) {  var colours = ['Black', 'White', 'Blue'];  var shapes = ['Square', 'Circle', 'Triangle'];  var names = ['John', 'David', 'Sarah'];
switch (ddl1.value) { case 'Colours': ddl2.options.length = 0; for (i = 0; i < colours.length; i++) { createOption(ddl2, colours[i], colours[i]); } break; case 'Shapes': ddl2.options.length = 0; for (i = 0; i < shapes.length; i++) { createOption(ddl2, shapes[i], shapes[i]); } break; case 'Names': ddl2.options.length = 0; for (i = 0; i < names.length; i++) { createOption(ddl2, names[i], names[i]); } break; default: ddl2.options.length = 0; break; }
}
function createOption(ddl, text, value) { var opt = document.createElement('option'); opt.value = value; opt.text = text; ddl.options.add(opt);}
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">  <option value=""></option>  <option value="Colours">Colours</option>  <option value="Shapes">Shapes</option>  <option value="Names">Names</option></select>
<select id="ddl2"></select>

Dynamically Populating Drop down list from selection of another drop down value

Hope this might help you.

JSFiddle : DEMO

HTML

<select name="meal" id="meal" onChange="changecat(this.value);">
<option value="" disabled selected>Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select name="category" id="category">
<option value="" disabled selected>Select</option>
</select>

JS

var mealsByCategory = {
A: ["Soup", "Juice", "Tea", "Others"],
B: ["Soup", "Juice", "Water", "Others"],
C: ["Soup", "Juice", "Coffee", "Tea", "Others"]
}

function changecat(value) {
if (value.length == 0) document.getElementById("category").innerHTML = "<option></option>";
else {
var catOptions = "";
for (categoryId in mealsByCategory[value]) {
catOptions += "<option>" + mealsByCategory[value][categoryId] + "</option>";
}
document.getElementById("category").innerHTML = catOptions;
}
}

There is a loop (for...in loop) in JavaScript, which would help you in this case

A for...in loop only iterates over enumerable properties. Objects
created from built–in constructors like Array and Object have
inherited non–enumerable properties from Object.prototype and
String.prototype, such as String's indexOf() method or Object's
toString() method. The loop will iterate over all enumerable
properties of the object itself and those the object inherits from its
constructor's prototype (properties closer to the object in the
prototype chain override prototypes' properties).

In each iteration one property from object is assigned to variable-name and this loop continues till all the properties of the object are exhausted.

For more Link

MVC (5) Populate a dropdown based on another

I have added NetFiddle example. Works here

I would suggest to use jquery $.getJson() to fill second dropdown without refresh to page. You can implement like following example.

//html

<select id="EventId" name="eventId">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
</select>

<label>Second</label>
<select id="SecondDropdown">
</select>

// jquery

$("#EventId").on("change", function(){
showValue($(this).val());
})

function showValue(val)
{
console.log(val);
$.getJSON('@Url.Action("GetDropdownList", "Home")' + "?value=" + val, function (result) {
$("#SecondDropdown").html(""); // makes select null before filling process
var data = result.data;
for (var i = 0; i < data.length; i++) {
$("#SecondDropdown").append("<option>"+ data[i] +"</option>")
}

})
}

//controller

[HttpGet]
public JsonResult GetDropdownList(int? value)
{
List<string> yourdata = new List<string>();

if(value == 2)
{
yourdata.Add("option2a");
yourdata.Add("option2b");
yourdata.Add("option2c");
return Json(new { data = yourdata}, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { data = ""}, JsonRequestBehavior.AllowGet);
}

}

Drop-down box dependent on the option selected in another drop-down box

Try something like this... jsfiddle demo

HTML

<!-- Source: -->
<select id="source" name="source">
<option>MANUAL</option>
<option>ONLINE</option>
</select>

<!-- Status: -->
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
</select>

JS

$(document).on('ready', function () {

$("#source").on('change', function () {
var el = $(this);
if (el.val() === "ONLINE") {
$("#status").append("<option>SHIPPED</option>");
} else if (el.val() === "MANUAL") {
$("#status option:last-child").remove();
}
});

});

Change dropdown based on another dropdown in Angular 11?

The change event should be changed to selectionChange. If you want the state to be auto-selected add [(ngModel)] to the state dropdown and update it when the country is changed:

 changeCountry(country: any) { 
this.states = this.Countries.find(
(cntry) => cntry.name == country.value
).states;
this.sFirst = this.states[0].name;
}
<mat-form-field>
<mat-select [(ngModel)]="custFirst" name="custFirst" placeholder="Country" (selectionChange)="changeCountry($event)">
<mat-option *ngFor="let country of Countries" [value]="country.name" > {{ country.name }}</mat-option>
</mat-select>
</mat-form-field>

<mat-form-field>
<mat-select placeholder="State" [(ngModel)]="stateFirst">
<mat-option *ngFor="let state of states" [value]="state.name">{{ state.name }}
</mat-option>
</mat-select>
</mat-form-field>

Working example: https://stackblitz.com/edit/angular-6-stackoverflow-nzvqse?file=src/app/components/stackoverflow-solution/stackoverflow-solution.component.ts

Fill drop down list on selection of another drop down list

Sample Image

Sample Image

Sample Image

Model:

namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}

Controller:

public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}

//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}

View:

@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";

$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});

}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">

</select>

<br /><br />
}

Updating dropdown based on previous dropdown selection

this would work with any number of dropdown.

you can generate random attributes to test.

$(document).ready(function () {    /* generates random attributes */    var div_attributes = $('#div_attributes');    var select_colors = $('#select_colors');    var select_sizes = $('#select_sizes');    var select_attr0 = $('#select_attr0');    var select_attr1 = $('#select_attr1');
$('#btnGenerate').on('click', function () { var result = "";
// var index = getRandomArbitrary(1, select_sizes.find('option').get().length); var random_attribute = select_sizes.find('option').eq(index).attr('value'); result += random_attribute;
// index = getRandomArbitrary(1, select_colors.find('option').get().length); random_attribute = select_colors.find('option').eq(index).attr('value'); result += '_' + random_attribute;
// index = getRandomArbitrary(1, select_attr0.find('option').get().length); random_attribute = select_attr0.find('option').eq(index).attr('value'); result += '_' + random_attribute;
// index = getRandomArbitrary(1, select_attr1.find('option').get().length); random_attribute = select_attr1.find('option').eq(index).attr('value'); result += '_' + random_attribute;
$('<div>' + result + '</div>').appendTo(div_attributes);
div_attributes.find('div').each(function () { var item = $(this); attributes.push(item.text()); }); SetFirstSelect(); });
var attributes = []; //sets first select SetFirstSelect(); function SetFirstSelect() { $.each(attributes, function (i, val) { var attribute = val.split('_')[0]; $('.attribute_price').eq(0).find('option[value="' + attribute + '"]').show(); }); } //control attributes array var selected_val = []; $('.attribute_price').on('change', function () { var item = $(this); var index = item.index('.attribute_price'); selected_val[index] = item.val(); var select = $('.attribute_price').eq(index + 1); var selected_attribute = item.val(); for (var i = index + 1; i < $('.attribute_price').get().length; i++) { $('.attribute_price').eq(i).find('option').hide(); $('.attribute_price').eq(i).prop('selectedIndex', 0) } var selected_val_str = selected_val[0]; for (var i = 1; i <= index; i++) { selected_val_str += '_' + selected_val[i]; } $.each(attributes, function (j, val) { if (val.indexOf(selected_val_str) >= 0) { var attribute1 = val.split('_')[index + 1];
select.find('option[value="' + attribute1 + '"]').show(); } }); });
function getRandomArbitrary(min, max) { return Math.floor(Math.random() * (max - min) + min); }});
.attribute_price option {            display: none;        }                .container {        margin:30px;        }                .row > div {        padding:10px;        }        .btn {        margin-top:20px;        }
<script  src="https://code.jquery.com/jquery-3.3.1.min.js"  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="  crossorigin="anonymous"></script>  <!-- Latest compiled and minified CSS --><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme --><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript --><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <div class="container"> <div class="row"> <div style="width:50%; float:left"> <input type="button" class="btn btn-primary" id="btnGenerate" value="generate random attributes" /> <div id="div_attributes"></div> </div> <div style="width:50%; float:left"> <div class="form-group"> <label>Sizes</label> <select class="form-control attribute_price" id="select_sizes"> <option value="">select size</option> <option value="small">small</option> <option value="large">large</option> <option value="medium">medium</option> </select> </div> <div class="form-group"> <label>color</label> <select id="select_colors" class="form-control attribute_price"> <option value="">select color</option> <option value="black">black</option> <option value="yellow">yellow</option> <option value="red">red</option> </select> </div> <div class="form-group"> <label>attrType0</label> <select id="select_attr0" class="form-control attribute_price"> <option value="">select attr0</option> <option value="attr00">attr00</option> <option value="attr01">attr01</option> <option value="attr02">attr02</option> </select> </div> <div class="form-group"> <label>attrType1</label> <select id="select_attr1" class="form-control attribute_price"> <option value="">select attr1</option> <option value="attr10">attr10</option> <option value="attr11">attr11</option> <option value="attr12">attr12</option> </select> </div> </div>
</div> </div>

Change dropdown options based on another dropdown angular

Bind first Dropdown To a property Departure

<h4>Airport of Departure</h4>
<select name="" id="" [(ngModel)] = "departure">
<option [value]="city.key" *ngFor="let city of opts">
{{city.key}}
</option>
</select>

In Typescript

public departure: string;

For Second Dropdown :-

<h4>Destination (must be different than departure location)</h4>
<select name="" id="">
<ng-container *ngFor="let city of opts">
<option [value]="city.key" *ngIf="city.key !== departure" >
{{ city.key }}
</option>
</ng-container>
</select>


Related Topics



Leave a reply



Submit