Home >Web Front-end >JS Tutorial >How to Populate One Dropdown Based on Selection in Another Using JavaScript?
When faced with the task of dynamically updating the options in one dropdown based on the selection made in another, it's essential to avoid unnecessary complexities like database queries. Let's explore a straightforward JavaScript-based solution that accomplishes this without the need for AJAX calls.
To illustrate this approach, consider a scenario where you have two dropdown lists: Dropdown A with options such as "Colors," "Shapes," and "Names" and Dropdown B. We want to populate the options in Dropdown B based on the selection made in Dropdown A.
The following JavaScript function demonstrates how to achieve this functionality:
<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); }
The following HTML markup includes two dropdown lists:
<code class="html"><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></code>
To use this functionality, simply call the configureDropDownLists function, passing the first dropdown (ddl1) and the second dropdown (ddl2) as arguments. The function will handle the dynamic population of Dropdown B based on the selection made in Dropdown A.
This code snippet demonstrates a complete working solution, allowing you to dynamically populate one dropdown based on the selection made in another using JavaScript, without the need for database calls or AJAX requests.
The above is the detailed content of How to Populate One Dropdown Based on Selection in Another Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!