[javascript] Change the content of a div based on selection from dropdown menu

Is there a simple way, using JavaScript, to dynamically show/hide content in a <div> based on the users selection from a drop down menu? For example, if a user selects option 1 then I would like <div> 1 to be displayed and all other <div>s to be hidden.

EDIT: Example HTML Setup

<select>
<option> Option 1</option>
<option> Option 2</option>
<option> Option 3</option>
<select>

<div id="content_1" style="display:hidden;">Content 1<div>
<div id="content_2" style="display:hidden;">Content 2<div>
<div id="content_3" style="display:hidden;">Content 3<div>

This question is related to javascript jquery html forms

The answer is


With zero jQuery

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <style>
.inv {
    display: none;
}
    </style>
    <body>
        <select id="target">
            <option value="">Select...</option>
            <option value="content_1">Option 1</option>
            <option value="content_2">Option 2</option>
            <option value="content_3">Option 3</option>
        <select>

        <div id="content_1" class="inv">Content 1</div>
        <div id="content_2" class="inv">Content 2</div>
        <div id="content_3" class="inv">Content 3</div>
        
        <script>
            document
                .getElementById('target')
                .addEventListener('change', function () {
                    'use strict';
                    var vis = document.querySelector('.vis'),   
                        target = document.getElementById(this.value);
                    if (vis !== null) {
                        vis.className = 'inv';
                    }
                    if (target !== null ) {
                        target.className = 'vis';
                    }
            });
        </script>
    </body>
</html>

Codepen

_x000D_
_x000D_
document
  .getElementById('target')
  .addEventListener('change', function () {
    'use strict';
    var vis = document.querySelector('.vis'),   
      target = document.getElementById(this.value);
    if (vis !== null) {
      vis.className = 'inv';
    }
    if (target !== null ) {
      target.className = 'vis';
    }
});
_x000D_
.inv {
    display: none;
}
_x000D_
<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8"/>
        <title></title>
    </head>
    <body>
        <select id="target">
            <option value="">Select...</option>
            <option value="content_1">Option 1</option>
            <option value="content_2">Option 2</option>
            <option value="content_3">Option 3</option>
        <select>

        <div id="content_1" class="inv">Content 1</div>
        <div id="content_2" class="inv">Content 2</div>
        <div id="content_3" class="inv">Content 3</div>
    </body>
</html>
_x000D_
_x000D_
_x000D_


The accepted answer has a couple of shortcomings:

  • Don't target IDs in your JavaScript code. Use classes and data attributes to avoid repeating your code.
  • It is good practice to hide with CSS on load rather than with JavaScript—to support non-JavaScript users, and prevent a show-hide flicker on load.

Considering the above, your options could even have different values, but toggle the same class:

<select class="div-toggle" data-target=".my-info-1">
  <option value="orange" data-show=".citrus">Orange</option>
  <option value="lemon" data-show=".citrus">Lemon</option>
  <option value="apple" data-show=".pome">Apple</option>
  <option value="pear" data-show=".pome">Pear</option>
</select>

<div class="my-info-1">
  <div class="citrus hide">Citrus is...</div>
  <div class="pome hide">A pome is...</div>
</div>

jQuery:

$(document).on('change', '.div-toggle', function() {
  var target = $(this).data('target');
  var show = $("option:selected", this).data('show');
  $(target).children().addClass('hide');
  $(show).removeClass('hide');
});
$(document).ready(function(){
    $('.div-toggle').trigger('change');
});

CSS:

.hide {
  display: none;
}

Here's a JSFiddle to see it in action.


Meh too slow. Here's my example anyway :)
http://jsfiddle.net/cqDES/

$(function() {
    $('select').change(function() {
        var val = $(this).val();
        if (val) {
            $('div:not(#div' + val + ')').slideUp();
            $('#div' + val).slideDown();
        } else {
            $('div').slideDown();
        }
    });
});

I am not a coder, but you could save a few lines:

<div>
            <select onchange="if(selectedIndex!=0)document.getElementById('less_is_more').innerHTML=options[selectedIndex].value;">
                <option value="">hire me for real estate</option>
                <option value="me!!!">Who is a good Broker? </option>
                <option value="yes!!!">Can I buy a house with no down payment</option>
                <option value="send me a note!">Get my contact info?</option>
            </select>
        </div>

<div id="less_is_more"></div>

Here is demo.


There are many ways to perform your task, but the most elegant are, I believe, using css. Here are basic steps

  1. Listening option selection event, biding adding/removing some class to container action, which contains all divs you are interested in (for example, body)
  2. Adding styles for hiding all divs except one.
  3. Well done, sir.

This works pretty well if there a few divs, since more elements you want to toggle, more css rules should be written. Here is more general solution, binding action, base on following steps: 1. find all elements using some selector (usually it looks like '.menu-container .menu-item') 2. find one of found elements, which is current visible, hide it 3. make visible another element, the one you desire to be visible under new circumstances.

javascript it a rather timtoady language )


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"