Using Jquery to populate dropdown menus

David Jones
@david3jones
avatar-davidejones

Populating dropdown menus using jquery can be done so easily i hadn’t really noticed until today. Its not something i’ve done for a while and the last time i did it was using regular javascript. Anyway i’ve just finish putting this in place on an intranet based cms system i’ve built and thought i’d throw it down here while its fresh in my mine. Its quite simple all you need to do is get a hold of your dropdown in jquery, use the change function to call a php file and thats it. Heres the code to do i created to do it starting with the jquery part

<script type="text/javascript">
    	$(function(){
    		$("#DocumentDepartmentId").change(function(){
    			var options = '';
    			$.getJSON("http://localhost/select.php",{id: $(this).val()}, function(data){
    			  for (var i = 0; i < data.length; i++) {
    				options += '<option value="' + data[i].optionValue + '">' + data[i].optionDisplay + '</option>';
    			  }
    			  $("select#DocumentFilecategoryId").html(options);
    			});
    		});
    	});
</script>

and heres the html, note that i actually had the second dropdown already on the page populated with the default values however you may want to have this hidden until the user actually changes the dropdown.

<select id="DocumentDepartmentId">
    	<option value="1">HR</option>
    	<option value="2" selected="selected">Health and Safety</option>
    	<option value="3">Business Development</option>
    	<option value="4">Quality Audits</option>
    	<option value="5">Helpdesk</option>
    	<option value="6">Finance</option>
</select>
<select id="DocumentFilecategoryId">
    	<option value="16">Tool Box Talks - Back Sheet</option>
    	<option value="4">H&amp;S Objectives and Strategy</option>
</select>

and lastly heres the select.php which takes the input id of the selected field and uses that to return some json that is used for the follow up dropdown.

$conn = mysql_connect("host","user","pass") or die(mysql_error());
mysql_select_db("db",$conn) or die(mysql_error());
$result = mysql_query("SELECT * FROM filecategories WHERE department_id = ".$_GET['id']) or die();
echo "[";
$x = 0;
while($row = mysql_fetch_array($result)){
    	if($x > 0) {
    		echo ",";
    	}
    	echo '{"optionValue":"'.$row['id'].'","optionDisplay":"'.$row['name'].'"}';
    	$x++;
}
if($x == 0) {
    	echo '{"optionValue":"0","optionDisplay":"No File Categories"}';
}
echo "]";
mysql_free_result($result);
mysql_close($conn);

Hope it helps and if anyone has any feedback, improvements or any comments please feel free to leave them

Comments

  • avatar-val
    # val

    hei can you help me?

    i have to do a 4 dropdowns menus.

    with parameters from 3 of them i want to populate the 4 one with data from db smt like this

    sql=“select from db where x=“dropdown1” AND y=‘dropdown2’ AND z= ‘dropdown3’”

    can you help me?

    I try to implement your code but it did.t work..

  • avatar-davidejones
    # davidejones
    You could use the same idea as my code but have some more php to determine what data to return based on the data passed to it from the ajax getjson call. I don’t have an example to hand but there should be plenty online.
  • avatar-alan
    # Alan

    Hi there

    I have tried this but my website does nothing when i change the dropdown box

    • avatar-davidejones
      # davidejones
      Make sure your php file is working and returning the right data check for any javascript errors in the browser and try inspecting the net requests in firebug. That should start to lead you in the direction of the problem

Comments are currently closed