Introduction to JQUERY – Populating / Creating Dynamic Dropdowns

Guest Posts Paolo Nikko Nuñal

There are times that you will have to populate dropdowns depending on the user's choice. More so, if you are planning to have a dynamic dropdown. Luckily, JQUERY can manipulate it easily depending on the user's choice. In this tutorial we are going to explore some combinations of JQUERY methods that you can apply on your dynamic forms. In this tutorial you are going to learn how to dynamically change the options on dropdowns using the combination of Arrays, append, find and remove methods.


<script src="">
             var PHONES = new Array("Sony","Samsung","HTC","Motorolla");
                for(i=0; i < PHONES.length; i++){
                     $("#dropdown").append('<option value="'+PHONES[i]+'">'+PHONES[i]+'</option>');
              var CARS = new Array("Ford","Honda","Toyota","Suzuki");
                  for(i=0; i < CARS .length; i++){
                      $("#dropdown").append('<option value="'+CARS [i]+'">'+CARS [i]+'</option>');
<select id="dropdown"></select>
<button type="button" id="btn-phones">Populate Phones</button>
<button type="button" id="btn-cars">Populate Cars</button>

In the example above, each button have its own corresponding array with data. The first one is Phones that contains the name of phone manufacturers while the other one is Cars that contains the name of car manufacturers. In our example, each button has its own trigger. For example, if you click on the Phone button, it will then initialize the Phone array with the corresponding value. After which it will iterate or loop all the content of the PHONES array and call the dropdown with the id="dropdown" to create a set of selections based on the array.

Since the array PHONES has four strings, it will loop four times and will append the <option> tag four times. The same as true on the CARS button. You might be wondering why the PHONES or CARS list of string doesn't continue on the dropdown, it is because we have used the methods find() and remove() to eliminate the existing <option> if any.

The find() has the parameter <option> in which it will locate every option on the dropdown and remove them with the remove() method.