How to Dynamically Populate Options on Dropdown Lists Based on Selection in Another Dropdown

Dynamically update a dropdown list based on another dropdown list?

You can use split(',') to split values then using for-loop you can get values from split array and finally use $("#beta option[value=" + vals + "]").show() to show options where values matches.

Demo Code:

$("#alpha").on("change", function() {
var values = $(this).val().split(',') //split value which is selected
$("#beta option").hide() //hide all options from slect box
//loop through values
for (var i = 0; i < values.length; i++) {
var vals = values[i]
$("#beta option[value=" + vals + "]").show()//show that option

}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<select class="browser-default" id="alpha">
<option value="a,b,c">One</option>
<option value="d">Two</option>
<option value="e,f">Three</option>
</select>

<select class="browser-default" id="beta">
<option selected="selected" value="">--select one-- </option>
<option value="a">First</option>
<option value="b">Second</option>
<option value="c">Third</option>
<option value="d">Fourth</option>
<option value="e">Fifth</option>
<option value="f">Sixth</option>
</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

Dynamically populate a DropdownList based on another DropDownList's selection

Actually it is possible to do it without AJAX but would still require some Javascript:

Both first and second dropdowns should have all the available options prerenderd. For each option on the second dropdown specify for what value of the first dropdown the option should be visible. For example:

<select id="firstDd">
<option value="car">Cars</option>
<option value="plane">Planes</option>
</select >

<select id="secondDd">
<option value="ferrari" data-display-on="car">Ferrari</option>
<option value="bugatti" data-display-on="car">Bugatti</option>
<option value="747" data-display-on="plane">Boeing 747</option>
<option value="757" data-display-on="plane">Boeing 757</option>
</select >

Now with some simple javascript you can toggle visibility of second dropdown options based on the value of first one:

$('#firstDd').change(function(){
var value = $(this).val();
if(value)
{
var $secondDd = $('#secondDd');
var $selectedOption = $('option:selected', $(this));
$('option', $secondDd).hide();
$('option[data-display-on="'+value+'"]',$secondDd).show();
}
$($secondDd).val(null);
})

$('#firstDd').change();

Here is working JSFiDDLE that demonstrates this approach

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>

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.

Dynamically populate second drop down menu based on first selection

Here is one approach - I have annotated the code to provide explanations of the main steps. Most of the complexity comes from (a) managing the relationship between the two selection widgets, and (b) handling the array of values from the multi-select.

// inline test data:
var dataSet = [
{
"id": "123",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"id": "456",
"name": "Donna Snider",
"position": "Customer Support",
"salary": "$112,000",
"start_date": "2011/01/25",
"office": "New York",
"extn": "4226"
},
{
"id": "567",
"name": "Cedric Kelly",
"position": "Senior Javascript Developer",
"salary": "$433,060",
"start_date": "2012/03/29",
"office": "Edinburgh",
"extn": "6224"
},
{
"id": "432",
"name": "Airi Satou",
"position": "Accountant",
"salary": "$162,700",
"start_date": "2008/11/28",
"office": "Tokyo",
"extn": "5407"
},
{
"id": "987",
"name": "Brielle Williamson",
"position": "Integration Specialist",
"salary": "$372,000",
"start_date": "2012/12/02",
"office": "New York",
"extn": "4804"
}
];

$(document).ready(function() {

var table = $('#example').DataTable( {
data: dataSet,
orderCellsTop: true,
columns: [
{ data: "name" },
{ data: "office" },
{ data: "position" },
{ data: "extn" }
],
initComplete: function () {
this.api().columns( [1, 2] ).every( function () {
var column = this;
var colIdx = column.index();
var node;
var select;
if (colIdx === 1) {
node = $('#office_select');
select = $('<select><option value=""></option></select>');
} else {
node = $('#position_select');
select = $('<select multiple><option value=""></option></select>');
}

select.appendTo( $(node).empty() )
.on( 'change', function () {
// the contents of the multi-select, as an array of values:
var val = $(this).val();
if (colIdx === 1) { // this is the standard select column (for "office")
val = $.fn.dataTable.util.escapeRegex(val);
column.search( val ? '^' + val + '$' : '', true, false ).draw();
rebuildPositionSelect();
} else { // this is the multi-select column (for "position"):
// build a string containing the pipe-separated multiselect values, but
// with each value escaped for any regex characters it may contain:
var vals = val.map(x => $.fn.dataTable.util.escapeRegex(x)).join('|');
column.search( vals ? '^' + vals + '$' : '', true, false ).draw();
}
} );

column.data().unique().sort().each( function ( val ) {
select.append( '<option value="' + val +'">' + val + '</option>' )
} );

} );
}
} );

function rebuildPositionSelect() {
var select = $('#position_select select').empty().append('<option value=""></option>');
// note the use of {search:'applied'} here, to only capture visible "position" values:
var column = table.column(2, {search:'applied'});
// we need to reset the "position" search back to "none", to unfilter that column,
// otherwise our new filter may not find the already filtered data:
column.search('').draw();
column.data().unique().sort().each( function ( val ) {
select.append( '<option value="' + val +'">' + val + '</option>' );
} );
}

} );
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">

</head>

<body>

<div style="margin: 20px;">

<div>
<span>Office: </span>
<span id="office_select"></span>
<span> Position: </span>
<span id="position_select"></span>
</div>

<br><br>

<table id="example" class="display dataTable cell-border" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Office</th>
<th>Position</th>
<th>Extn.</th>
</tr>
</thead>
</table>

</div>

</body>
</html>


Related Topics



Leave a reply



Submit