HTML5 Zone is brought to you in partnership with:

Raymond Camden is a developer evangelist for Adobe. His work focuses on web standards, mobile development and Cold Fusion. He's a published author and presents at conferences and user groups on a variety of topics. He is the happily married proud father of three kids and is somewhat of a Star Wars nut. Raymond can be reached via his blog at www.raymondcamden.com or via email at raymondcamden@gmail.com Raymond is a DZone MVB and is not an employee of DZone and has posted 216 posts at DZone. You can read more from them at their website. View Full User Profile

jQuery Example: Related, hidden selects

02.12.2013
| 2003 views |
  • submit to reddit

This request came in from a reader and I thought I'd share it. I'm not sure how re-usable it is for others, nor will I promise that it is The Best jQuery Code ever. (Far from it.) But on the off chance the example helps others, I wanted to post it.

The reader had a simple request - set up related selects. I've done this many times before so that part wasn't such a big deal. The only twist here is that he wanted the related selects to only show up when selected.

His data supported, at most, three levels of options. But not every option would have three levels.

Because of this restriction, I decided to simply build my code to support three levels total and not build some high level, super cool, infinite deep relation type doohicky. As it stands, if I were to see 4 or more related selects on a form I'd run away screaming.

Let's then start off with the HTML portion of the code.

<body>

  <form>
		
		Main: 
		<select id="mainDD">
			<option value="">Select Main Option</option>
			<option value="a">A</option>
			<option value="b">B</option>
			<option value="c">C</option>
			<option value="d">D</option>
		</select><br/>
		
		<div id="secondDiv" style="display:none">
			Second:
			<select id="secondDD">
				
			</select>
		</div>

		<div id="thirdDiv" style="display:none">
			Third: 
			<select id="thirdDD">
				
			</select>
		</div>

	</form>
	
</body>

You can see my three drop downs in the form block. The second and third drop downs are wrapped in DIV tags and hidden with CSS. Notice too that I've added in the drop downs with no options. The idea here is that I'll use jQuery to hide and manipulate the contents of these tags. Let's look at the code now.

$(document).ready(function() {
  
	//cache some selections
	var mainDD = $("#mainDD");
	var secondDD = $("#secondDD");
	var secondDiv = $("#secondDiv");
	var thirdDD = $("#thirdDD");
	var thirdDiv = $("#thirdDiv");
	
	mainDD.on("change", function(e) {
		var selected = $(this).val();
		console.log(selected);
		
		//First, trigger a hide of all the child selects
		secondDiv.hide();
		thirdDiv.hide();
		
		//Second, we only get crap if val != ''
		if(selected === "") return;
		
		//Get our data using a hackish dynamic url
		$.get("data/"+selected + ".json", {}, function(result) {
			console.dir(result);	
			populateSelect(secondDD, result);
			secondDiv.show();
		}, "JSON");
		
	});
	
	secondDD.on("change", function(e) {
		var selected = $(this).val();
		console.log(selected);
		
		//First, trigger a hide of all the child selects
		thirdDiv.hide();
		
		//Second, we only get crap if val != ''
		if(selected === "") return;
		
		//Get our data using a hackish dynamic url
		$.get("data/"+selected + "_children.json", {}, function(result) {
			console.dir(result);	
			if(result.length) {
				populateSelect(thirdDD, result);
				thirdDiv.show();
			}
		}, "JSON");
		
	});
				
	function populateSelect(dom, options) {
		console.log('running populateSelect');
		dom.html("");
		var s = "<option value=\"\">Select Option</option>";
		for(var i=0, len=options.length; i<len; i++) {
			s += "<option value=\"" + options[i] + "\">" + options[i] + "</option>";	
		}
		dom.html(s);
	}
	
});

First up is a set of code used to cache my selectors. This is a general jQuery best practice.

I then have change handlers for my two drop downs. (Remember, we only support three levels max. As I said, you could possibly build something fancy that supported N levels, but I'm one of those crazy people who like simple solutions.) In general, both handlers are pretty similar.

They get the value from the drop down and then automatically hide anything "beneath" them. For the first drop down this is both of the related divs. For the second it is only the third.

If a value was selected, an AJAX call is fired off. Typically this would be to a dynamic datasource. To keep things simple I just built some basic static JSON files that return arrays. I can then take that array and populate a select. Note that I abstracted that logic in populateSelect().

And that's pretty much it. Not rocket science, but maybe useful. You can play with the demo by clicking the ginormous button below. This was tested in Chrome, Firefox, and IE10.


Published at DZone with permission of Raymond Camden, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)