Populate One Dropdown List Based on the Selection of Other Dropdown List

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>

Populate one dropdown list based on another dropdown list

Bind a change event handler and populate second select tag based on selected value.

var diction = {  A1: ["B1", "B2", "B3"],  A2: ["B4", "B5", "B6"]}
// bind change event handler$('#A').change(function() { // get the second dropdown $('#B').html( // get array by the selected value diction[this.value] // iterate and generate options .map(function(v) { // generate options with the array element return $('<option/>', { value: v, text: v }) }) ) // trigger change event to generate second select tag initially}).change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form id="dynamicForm">  <select id="A">    <option value="A1">A1</option>    <option value="A2">A2</option>  </select>  <select id="B">  </select></form>

Populate one dropdown list based on the selection of other dropdown list

WORKING DEMO http://jsfiddle.net/kasperfish/r7MN9/3/ (with jquery)

cars=new Array("Mercedes","Volvo","BMW","porche");
phones=new Array('Samsung','Nokia','Iphone');

populateSelect();

$(function() {

$('#cat').change(function(){
populateSelect();
});

});

function populateSelect(){
cat=$('#cat').val();
$('#item').html('');

if(cat=='car'){
cars.forEach(function(t) {
$('#item').append('<option>'+t+'</option>');
});
}

if(cat=='phone'){
phones.forEach(function(t) {
$('#item').append('<option>'+t+'</option>');
});
}

}

UPDATED: using eval() to be able to add as much arrays as you want.
JSFIDDLE DEMO

cars=new Array("Mercedes","Volvo","BMW","porche");
phones=new Array('Samsung','Nokia','Iphone');
names=new Array('Kasper','Elke','Fred','Bobby','Frits');
colors=new Array('blue','green','yellow');

populateSelect();

$(function() {

$('#cat').change(function(){
populateSelect();
});

});

function populateSelect(){
cat=$('#cat').val();
$('#item').html('');

eval(cat).forEach(function(t) {
$('#item').append('<option>'+t+'</option>');
});
}

how to populate dropdown list based on previous dropdown selected value

You can use change event on your select-box . Inside this get value of selected option using $(this).val() this will return you array so use for-loop to iterate through value and show options where value matches in second dropdown . Lastly refresh your selectpicker to update changes .

Demo Code :

$('#id1').on('change', function(e) {
var values = $(this).val()
$("#id2 option").hide() //hide all options
$('#id2').selectpicker('deselectAll') //if want to remove all selcted optn
if (values.length > 0) {
for (var i = 0; i < values.length; i++) {
//show where value is same..
$("#id2 option[value=" + values[i] + "]").show()
}
} else {
$("#id2 option").show() //show all options
}
$('#id2').selectpicker('refresh'); //refresh selctpicker
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>
<select id="id1" name="name1" class="selectpicker" data-style="form-control" data-live-search="true" title="Select Fruits" multiple="multiple">
<option value="Fruit">Fruits</option>
<option value="Animal">Animal</option>
</select>
<select id="id2" name="name2" class="selectpicker" data-style="form-control" data-live-search="true" title="Select Product" multiple="multiple">
<option value="Fruit">Mangoes</option>
<option value="Fruit">Apple</option>
<option value="Animal">Dog</option>
<option value="Animal">Cat </option>

</select>

Populate dropdown list upon selecting a value from another dropdown list

change your city_stats method like. This method should return id and name

def city_stats
@state = params[:state]
@cities = City.where(:state => state).select(:id, :name)

respond_to do |format|
format.json { render :json => @cities }
end
end

Change your each function in ajax call like this.Since data in response is array of object we are using value.id, value.name .

$.each(data,function(key, value) { 
listitems += '<option value="' + value.id + '">' + value.name + '</option>';
});

How do I fill a drop down-list based on selection by another drop-down list ASP.NET

UPDATE 24/07

Here is the result of mini version.
Sample Image

If it meets your needs, you could follow the steps below to accomplish it.

  1. Model

There's no need to add PreferenceTypein StaffPreferenceModel because it's only used to display the group of PreferenceValue.

public class StaffPreferenceModel
{
[Key]
[Display(Name = "Staff Preference ID")]
public Guid StaffPreferenceID { get; set; }

[Display(Name = "Preference Value ID")]
public Guid PreferenceValueID { get; set; }

[ForeignKey("PreferenceValueID")]
public PreferenceValueModel PreferenceValue { get; set; }

}

public class PreferenceTypeModel
{
[Key]
[Display(Name = "Preference Type ID")]
public Guid PreferenceTypeID { get; set; }

[Display(Name = "Preference Type")]
public string PreferenceName { get; set; }
}

public class PreferenceValueModel
{
[Key]
[Display(Name = "Preference Value ID")]
public Guid PreferenceValueID { get; set; }

[Display(Name = "Preference Value")]
public string Value { get; set; }

[Display(Name = "Preference Type ID")]
public Guid PreferenceTypeID { get; set; }

[ForeignKey("PreferenceTypeID")]
public PreferenceTypeModel PreferenceTypes { get; set; }
}

  1. Controller
    public IActionResult Create()
{
ViewData["PreferenceTypeID"] = new SelectList(_context.PreferenceTypeModel, "PreferenceTypeID", "PreferenceName");

//list preference values by default type
var preferenceValues = _context.PreferenceValueModel.Where(p=>p.PreferenceTypeID == _context.PreferenceTypeModel.FirstOrDefault().PreferenceTypeID);
ViewData["PreferenceValueID"] = new SelectList(preferenceValues, "PreferenceValueID", "Value");

return View();
}

[HttpPost]
public async Task<List<PreferenceValueModel>> GetPreferenceValues(Guid id)
{
var PreferenceValues = _context.PreferenceValueModel.Where(p => p.PreferenceTypeID == id).ToList();
return PreferenceValues;
}

  1. View
    <form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>

<div class="form-group">
<label class="control-label">PreferenceType</label>
<select id="PreferenceType" class="form-control" asp-items="ViewBag.PreferenceTypeID"></select>
</div>

<div class="form-group">
<label asp-for="PreferenceValueID" class="control-label"></label>
<select asp-for="PreferenceValueID" class="form-control" asp-items="ViewBag.PreferenceValueID"></select>
</div>

<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>

Use js to get preference values when PreferenceType dropdownlist selected.

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#PreferenceType").change(function () {
$("#PreferenceValueID").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("GetPreferenceValues")', // we are calling json method
dataType: 'json',
data: { id: $("#PreferenceType").val() },
success: function (states) {
// states contains the JSON formatted list
// of states passed from the controller

$("#PreferenceValueID").append('<option value="' + "0" + '">' + "Select PreferenceValue" + '</option>');
debugger;
$.each(states, function (i, state) {
$("#PreferenceValueID").append('<option value="' + state.preferenceValueID + '">' + state.value + '</option>');
// here we are adding option for States
});

},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>

Cascading a DropDownList with another DropDownList in ASP.Net.

Please try to read this article and if you are using razor pages in MVC, read this article.

The main steps:

  1. Create Entity Data Model (Preference and StaffPreference)

  2. Adding View Model (PreferenceView)

    public class PreferenceView
    {
    public int PreferenceId { get; set; }
    public List<Preference> PreferenceList { get; set; }
    public List<StaffPreference> StaffPreferenceList { get; set; }
    }
  3. Create action to return view with PreferenceView.

    Create a GetStaffPreferenceByType method to return StaffPreferenceList by type.

  4. Adding jQuery Ajax script for binding State dropdownlist.

Populating Drop down list from selection to another drop down value not show

Using a completely customisable way:

let data = [{"id":1,"name":"USA","parentid":0},
{"id":2,"name":"Japan","parentid":0},
{"id":3,"name":"Europe","parentid":0},
{"id":4,"name":"California","parentid":1},
{"id":5,"name":"Oklahoma","parentid":1},
{"id":6,"name":"Arizona","parentid":1},
{"id":7,"name":"Kantô","parentid":2},
{"id":8,"name":"Kansai","parentid":2},
{"id":9,"name":"Chügoku","parentid":2},
{"id":10,"name":"France","parentid":3},
{"id":11,"name":"Deutschland","parentid":3},
{"id":12,"name":"Espana","parentid":3},
{"id":13,"name":"Sacramento","parentid":4},
{"id":14,"name":"Los Angeles","parentid":4},
{"id":15,"name":"San Diego","parentid":4},
{"id":16,"name":"Tulsa","parentid":5},
{"id":17,"name":"Oklahoma City","parentid":5},
{"id":18,"name":"Lawton","parentid":5},
{"id":19,"name":"Phoenix","parentid":6},
{"id":20,"name":"Flagstaff","parentid":6},
{"id":21,"name":"Tucson","parentid":6},
{"id":21,"name":"Tokyo","parentid":7},
{"id":22,"name":"Chiba","parentid":7},
{"id":23,"name":"Tochigi","parentid":7},
{"id":24,"name":"Kyoto","parentid":8},
{"id":25,"name":"Osaka","parentid":8},
{"id":26,"name":"Nara","parentid":8},
{"id":27,"name":"Tottori","parentid":9},
{"id":28,"name":"Hirochima","parentid":9},
{"id":29,"name":"Okayama","parentid":9},
{"id":30,"name":"Quimper","parentid":10},
{"id":31,"name":"Toulouse","parentid":10},
{"id":32,"name":"Nancy","parentid":10},
{"id":33,"name":"Dusseldorf","parentid":11},
{"id":34,"name":"Leipzig","parentid":11},
{"id":35,"name":"Munchen","parentid":11},
{"id":36,"name":"Barcelona","parentid":12},
{"id":37,"name":"Sevilla","parentid":12},
{"id":38,"name":"Guernica","parentid":12}]

function populateList(list, pid) {
let l = document.getElementById(list);
l.innerHTML = "";
let topItem = document.createElement("option");
topItem.value = 0;
topItem.text = "--Select--";
l.appendChild(topItem);
let items = data.filter(item => item.parentid == pid);
items.forEach(function(item){
let newItem = document.createElement("option");
newItem.value = item.id;
newItem.text = item.name;
l.appendChild(newItem);
})
}

function updateList(selList, thisList) {
if (thisList.value != 0) {
populateList(selList, Number(thisList.value));
} else {
let s = document.getElementById(selList);
s.value = 0;
triggerEvent(s, "onchange");
let sCopy = s.cloneNode(false);
let p = s.parentNode;
p.replaceChild(sCopy, s);
}
}
function triggerEvent(e, trigger)
{
if ((e[trigger] || false) && typeof e[trigger] == 'function')
{
e[trigger](e);
}
}


function loadList1() {
populateList("list1", 0);
}

window.onload = loadList1;
select {width:150px;}
Region: <select id="list1" onchange="updateList('list2', this);"></select>
Sub-region:<select id="list2" onchange="updateList('list3', this);"></select>>
Location:<select id="list3"></select>

How to populate a dropdown list based on the choice i've made in another dropdown list?

This code is in the "SelectionChanged" event of my ddlb_division object. I have 2 DDLB's, ddlb_division & ddlb_section.

int li_division_id
int li_section_id
string ls_section

SetPointer(HourGlass!)

//Clears the DDLBs
ddlb_section.Reset()

//Gets the Division ID
li_division_id = integer(Left(this.Text(index), 2))

//Cursor to gather the Sections under the selected Division
declare section cursor for
select section_id, section_name
from tadtp_sections
where division_id = :li_division_id;

//Open cursor
open section;

//Get first row of data
fetch section into :li_section_id, :ls_section;

//Loop while we have rows
do while(SQLCA.SQLCode = 0)

//Adds item to DDLB
ddlb_section.AddItem(string(li_section_id, "00") + " " + Trim(ls_section))

//Gets next row
fetch section into :li_section_id, :ls_section;

loop

//Close cursor
close section;

//Enables controls
ddlb_section.Enabled = true


Related Topics



Leave a reply



Submit