Show / Hide Elements with JavaScript

If you would like to show / hide certain elements of your page based on user action, such as clicking a button or choosing a value from a select box, you can use JavaScript to achieve your task.

The first thing we need to do is decide which user action will cause elements to appear / disappear on the page.  Lets say, for example, that we we want to show a disclaimer, and only allow the user to continue if they agree to the disclaimer. We will create two radio buttons, and one submit button:

Do you agree to the terms of our disclaimer?
<input type="radio" name="agree" value="y" /> Yes
<input type="radio" name="agree" value="n" /> No
<br />
<input type="submit" id="continue" value="Continue" />

Now, lets start building the JavaScript.  At the end of your HTML file, lets define the following script:

var continue_button = document.getElementById('continue'); = 'hidden';

So far, the script we just created will cause the Continue button to disappear once the page is loaded.

Now, we want the user to be able to see the Continue button if they choose ‘Yes’ from the radio button group.  We also want the Continue button to disappear again if they choose the ‘No’ radio button.

Let’s modify our code above by assigning click event handlers to both radio buttons:

<input type="radio" name="agree" value="y" onClick="toggle(this)" /> Yes
<input type="radio" name="agree" value="n" onClick="toggle(this)" /> No

Now, when a user clicks either ‘Yes’ or ‘No’, the JavaScript toggle function will be called, and the current agree object will be passed to the function with the thiskeyword.  Let’s define the toggle function and add it to our existing JavaScript above:

var continue_button = document.getElementById('continue'); = 'hidden';

function toggle(switchElement) {
  if (switchElement.value == 'y') = 'visible';
  else = 'hidden';

A few notes:

  • Notice that we define continue_button outside of the toggle function.  We do this so that document.getElementById only needs to be called once for each page load.  Had you defined continue_button inside the toggle function, the script would have to retrieve the Continue button element and assign it to a JavaScript variable each time you call toggle.
  • You could have also set the visibility of the Continue button with the HTML style attribute as follows:

<input type="submit" id="continue" value="Continue" style="visibility: hidden;" />