In this article you will learn how to show and hide divs or any other content on a page when clicking on a radio button using Javascript. You will learn:

  • how to create a function
  • how to create variables
  • how to use if/else if statements

First let’s create a simple css class:

Copy to Clipboard

We will use this to initially hide the content we want to use. Let’s create the input fields:

Copy to Clipboard

Below the input fields let’s add the DIVs we want to show and hide:

Copy to Clipboard

By default we add the hide-stuff class to each div so they are not displayed on page load.

Now we need to store the two input fields and the two DIVs in variables:

Copy to Clipboard

Now let’s create a function to hide and reveal the content:

Copy to Clipboard

So here we create a function called showHideDiv and first check if the first radio button is checked or not. For this we use the checked property which is a boolean and will have a value of true if checked.

If the condition is true, then we’ll remove the hide-stuff css class from the first div and add it to the second. The else if condition works the same way but the other way around and here we check whether the second radio button was checked.

Now that we have our function ready, we need to update our input fields and add an onclick event to it.

Copy to Clipboard