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.

Code:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
        $("#btn-phones").click(function(){
             var PHONES = new Array("Sony","Samsung","HTC","Motorolla");
                $("#dropdown").find('option').remove();
                for(i=0; i < PHONES.length; i++){
                     $("#dropdown").append('<option value="'+PHONES[i]+'">'+PHONES[i]+'</option>');
                 }
        });
        $("#btn-cars").click(function(){
              var CARS = new Array("Ford","Honda","Toyota","Suzuki");
                  $("#dropdown").find('option').remove();
                  for(i=0; i < CARS .length; i++){
                      $("#dropdown").append('<option value="'+CARS [i]+'">'+CARS [i]+'</option>');
                   }
         });
});
</script>
</head>
<body>
<select id="dropdown"></select>
<button type="button" id="btn-phones">Populate Phones</button>
<button type="button" id="btn-cars">Populate Cars</button>
</body>
</html>


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.