DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Frameworks
  4. jQuery Example: Related, hidden selects

jQuery Example: Related, hidden selects

Raymond Camden user avatar by
Raymond Camden
·
Feb. 12, 13 · Interview
Like (0)
Save
Tweet
Share
3.65K Views

Join the DZone community and get the full member experience.

Join For Free

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.


JQuery

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • OpenID Connect Flows
  • Choosing the Best Cloud Provider for Hosting DevOps Tools
  • DevOps Roadmap for 2022
  • The Top 3 Challenges Facing Engineering Leaders Today—And How to Overcome Them

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: