Save 15% on our Pro WordPress plugins with discount code: LAUNCH2021
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 = Creative thinker. Passionate about free and open Web.
The Tao of WordPress: Master the art of WordPress.

Leave a reply

Name and email required. Email kept private. Basic markup allowed. Please wrap any small/single-line code snippets with <code> tags. Wrap any long/multi-line snippets with <pre><code> tags. For more info, check out the Comment Policy and Privacy Policy.

Subscribe to comments on this post

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 »
Digging Into WordPress: Take your WordPress skills to the next level.
Thoughts
WP 5.8 Gutenberg/Block Widgets is breaking many sites. Fortunately Disable Gutenberg makes it easy to restore Classic Widgets with a click.
Easily the most common exploit scan for WordPress is /{path}/wp-login.php.
Pushing 110+ ℉ for several days now, expected for at least another week or so.
After 12 intense weeks the Plugin Planet redesign is now live. Much work still happening behind the scenes.
June, July, August historically are slow months on the Web. Perfect time to get some real work done (think projects).
Redesigning Plugin Planet is one the most challenging things I’ve done online. Almost there, about another two weeks ’til launch.
I could listen to Mouse Rat all day.
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.