Home >Web Front-end >JS Tutorial >How to Populate Dropdown Contents Dynamically Using JavaScript?
Dynamic Dropdown Population via Javascript
In a scenario where you need to populate the contents of one dropdown (B) based on the selection made in another dropdown (A) using JavaScript, there's no need for complex AJAX queries. Instead, you can leverage the following code snippet to accomplish this:
<code class="javascript">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); }
To utilize this code, include it in your JavaScript file and register the configureDropDownLists function as the onChange event handler for your first dropdown (A):
<code class="html"><select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))"> <option value="" selected>Select</option> <option value="Colours">Colours</option> <option value="Shapes">Shapes</option> <option value="Names">Names</option> </select> <select id="ddl2"> </select></code>
This code demonstrates how to populate the second dropdown (ddl2) based on the selection in the first dropdown (ddl1), utilizing switch-case logic to dynamically determine the content of ddl2.
The above is the detailed content of How to Populate Dropdown Contents Dynamically Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!