Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
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.

About the Author
Jeff Starr = Web Developer. Book Author. Secretly Important.
Banhammer: Protect your WordPress site against threats.
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 »
GA Pro: Add Google Analytics to WordPress like a pro.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.