Save 25% on our pro plugins with coupon code: SPRING2023
Web Dev + WordPress + Security

Vanilla JavaScript Toggle Divs Based on Radio Select Inputs

Working on the redesign of Plugin Planet, I needed a way to toggle between two divs based on which radio input is selected. This is useful for showing option-specific information conditionally, depending on the current active radio select field. This tutorial shows how to achieve it using vanilla JavaScript, so there is no need for including an entire library like jQuery. Very simple technique, requiring minimal amount of HTML markup and vanilla JavaScript.

Step 1: Add the HTML

Here is the example markup we’ll be working with:

<div class="first">
	
	<input class="r1" type="radio" name="first" checked>
	<input class="r2" type="radio" name="first">
	
	<div class="d1">Div 1</div>
	<div class="d2">Div 2</div>
	
</div>

This is the absolute minimal markup required for the technique to work. So you will want to customize further and adapt to your specific needs. For example, probably a good idea to add label tags to go with each of the radio inputs.

Step 2: Add the JavaScript

Once the HTML is added, the next step is to add the vanilla JavaScript:

// toggle divs via radio inputs
// tutorial @ https://m0n.co/12

(function() {
	toggleDivs();
})();
	
function setDisplay(d1, d2) {
	
	if (d1.style.display === 'none') {
		d1.style.display = 'block';
		d2.style.display = 'none';
	} else {
		d1.style.display = 'none';
		d2.style.display = 'block';
	}
}

function toggleDivs() {
	
	['.first'].forEach(item => {
		
		var r1 = document.querySelector(item + ' .r1');
		var r2 = document.querySelector(item + ' .r2');
		
		var d1 = document.querySelector(item + ' .d1');
		var d2 = document.querySelector(item + ' .d2');
		
		if (
			(typeof(r1) != 'undefined' && r1 != null) && 
			(typeof(r2) != 'undefined' && r2 != null) && 
			(typeof(d1) != 'undefined' && d1 != null) && 
			(typeof(d2) != 'undefined' && d2 != null)
		) {
			
			setDisplay(d1, d2);
			
			[r1, r2].forEach(item => {
				item.addEventListener('change', event => {
					setDisplay(d1, d2);
				});
			});
			
		}
		
	});
	
}

Here is what is happening with this code:

  1. First three lines are simply calling the function on the page.
  2. The next function setDisplay() is a helper function that basically handles the toggling of display block and none for the divs.
  3. The third function is where the action happens. It loops through an array of container divs, gets the required elements, checks that they exist, and then sets their display property using the previous function.

I’m not an expert in JavaScript, so there probably is a cleaner/better way of writing the above script. If you have any suggestions, feel free to share in the comments or via my contact form.

Step 3: Done!

The nice thing about this technique, it’s extensible. So you can include as many toggling radio/divs as needed on the page, and each will operate independently of the others. Let’s look at an example, where a second set of radio/divs is added. First, to the above markup, add the following second div:

<div class="second">
	
	<input class="r1" type="radio" name="second" checked>
	<input class="r2" type="radio" name="second">
	
	<div class="d1">Div 1</div>
	<div class="d2">Div 2</div>
	
</div>

Notice the class given to the container, .second. So now we can just add that class to the array in our loop function, like so:

['.first', '.second'].forEach(item => { ...

You can add as many containers (sets of radio/divs) as needed. Just give them each a different class, and make sure the radio names are unique for each set. For example, the first set of radio/divs both have first as the radio name, while the second set of radio/divs both have second as the radio name. Etc.

Jeff Starr
About the Author
Jeff Starr = Designer. Developer. Producer. Writer. Editor. Etc.
USP Pro: Unlimited front-end forms for user-submitted posts and more.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
USP Pro: Unlimited front-end forms for user-submitted posts and more.
Thoughts
Excellent (and free) tool to test your site's SSL configuration.
Plugin updates! All of our free and pro plugins ready for WordPress 6.2.
Daylight savings is a complete waste of time and needs to be eliminated.
Got a couple of snow days here in mid-March. Fortunately it's not sticking.
I handle all email in real time as it comes in, perpetually clear inbox for years now.
Added some nice features to Wutsearch search engine launchpad. Now 21 engines!
.wp TLD plz :)
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.