Dynamically Populating Drop Down List from Selection of Another Drop Down Value

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 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>

How can I populate dropdown values dynamically based on prior selection?

Loop through the array of details for the product name to get the versions.

The filename property should be an array so you can have multiple files for each version.

var ProductNameMap = {  "ProductA": [{"version": "1.0.0", "fileName": ["FileA1.zip", "FileA11.zip"]}, {"version": "1.0.1", "fileName": ["FileA2.zip", "FileA22.zip"]}],  "ProductB": [{"version": "3.5.0", "fileName": ["FileB1.zip", "FileB11.zip"]}, {"version": "4.0.1", "fileName": ["FileB2.zip", "FileB22.zip"]}],  "ProductC": [{"version": "1.0.0", "fileName": ["FileC1.zip", "FileC11.zip"]}, {"version": "1.0.1", "fileName": ["FileC2.zip", "FileC22.zip"]}]};
function PrepopulateProductName() { var ProductNameselect = document.getElementById('selProductName'); var i = 1; for (var selProductName in ProductNameMap) { ProductNameselect.options[i++] = new Option(selProductName) }}
function changeProductName(productNameID) { var versionSelect = document.getElementById('selProductVersion'); versionSelect.innerHTML = '<option>--Choose Product Version</option>'; // Remove previous options var fileSelect = document.getElementById('selFileName'); fileSelect.innerHTML = '<option>--Choose Filename</option>'; // Remove previous options var versions = ProductNameMap[productNameID]; for (var i = 0; i < versions.length; i++) { versionSelect.appendChild(new Option(versions[i].version)); }}
function changeProductVersion(productVersion) { var productNameID = document.getElementById('selProductName').value; var fileSelect = document.getElementById('selFileName'); fileSelect.innerHTML = ''; // Remove previous options var versions = ProductNameMap[productNameID]; for (var i = 0; i < versions.length; i++) { if (versions[i].version == productVersion) { var filenames = versions[i].fileName; for (var j = 0; j < filenames.length; j++) { fileSelect.appendChild(new Option(filenames[j])); } break; } }}

PrepopulateProductName();
Product Name:<select id="selProductName" name="selProductName" onchange="changeProductName(this.value);">  <option>--Choose Product Name--</option></select><br>Product Version:<select id="selProductVersion" name="selProductVersion" onchange="changeProductVersion(this.value);"></select><br>File Name:<select id="selFileName" name="selFileName"></select>

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>

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>

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>

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

Populating Drop down list from selection to label value

One way is to stored the urgency value in data array

if no item have a parent id equal to the current id (if you are on the last level of your data structure) you just have to recover and display the urgency column

l.innerText = item.urgency;

let data = [{"id":1,"name":"Infimos","parentid":0, "urgency": "low"},
{"id":2,"name":"Computer servicing","parentid":0, "urgency": "medium"},
{"id":3,"name":"Software installation","parentid":0, "urgency": "urgent"},
{"id":4,"name":"Fix errors","parentid":1, "urgency": "low"},
{"id":5,"name":"New feature","parentid":1, "urgency": "medium"},
{"id":6,"name":"Add payee","parentid":1, "urgency": "urgent"},
{"id":7,"name":"Add user","parentid":1, "urgency": "low"},
{"id":8,"name":"System assistance","parentid":1, "urgency": "medium"},
{"id":9,"name":"Internet connection problem","parentid":2, "urgency": "urgent"},
{"id":10,"name":"Computer malfunction","parentid":2, "urgency": "low"},
{"id":11,"name":"Printer connection problem","parentid":2, "urgency": "medium"},
{"id":12,"name":"Install microsoft office","parentid":3, "urgency": "urgent"},
{"id":13,"name":"Printer/scanner Installation","parentid":3, "urgency": "low"},
{"id":14,"name":"Install other applications","parentid":3, "urgency": "low"},
]

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);
});
if (!items.length) {
let item = data.filter(item => item.id == pid)[0];
l.innerText = item.urgency;
}
}

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 loadCat1() {
populateList("cat1", 0);
}

window.onload = loadCat1;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Category 1 <select id="cat1" name="cat1" onchange="updateList('cat2', this);">
<option></option>
</select>
<br><br>

Category 2<select class="form-select" required="" aria-label="select example" id="cat2" name="cat2" onchange="updateList('resultData', this);">
<option></option>
</select>

<br><br>
Result must low or medium or urgent : <p id="resultData"></p>


Related Topics



Leave a reply



Submit