NewbieX
NewbieX

Reputation: 19

Need to display/hide Divs when clicked sequentially

II revised a script I found on line but am struggling to get it to display the way I want. I am not sure how to modify the script to accomplish the following.

When web page opens only this shows:

Click on links below to find the mayor of your city
States

When the user clicks on States, only this shows:

Select a State
Alabama
Texas
California

When the user clicks on Alabama only the following shows:

Select a City
Birmingham
Auburn
Montgomery

When the user clicks on Birmingham only the following shows:

The mayor of Birmingham Alabama is William Bell

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<p><b>Click on links below to find the mayor of your city</b></p>

<p id="demo" onclick="myFunction('myDIV')">States</p>
<div id="myDIV">
<p><b> Select a State</b></p>
<p id="demo" onclick="myFunction('myDIV2')">Alabama</p>
<p id="demo" onclick="myFunction(myDIV3')">Texas</p>
<p id="demo" onclick="myFunction(myDIV4')">California</p>
</div>
<div id="myDIV2">
<p><b>Select a City</b></p>
<p id="demo" onclick="myFunction('myDIV2A')">Birmingham</p>
<p id="demo" onclick="myFunction('myDIV2B')">Auburn</p>
<p id="demo" onclick="myFunction('myDIV2C')">Montgomery</p>
</div>
<div id="myDIV2A">
<p><b>The mayor of Birmingham Alabama is William Bell</b></p>
</div>

<script>
function myFunction(div) {
	var x = document.getElementById(div);
	if (x.style.display === 'none') {
		x.style.display = 'block';
	} else {
		x.style.display = 'none';
	}
}
</script>

</body>
</html>

Upvotes: 0

Views: 1011

Answers (4)

We have a few things to fix in your code, but don't worry, it will be easy!

First, check the line:

var x = document.getElementById(div);

The .getElementById() function will look for elements with an id of "div", but there is no div with id="div" in your code. You have divs with id="demo", one with id="myDiv", another with id="myDiv2" and one last div with id="myDiv2A". Since you don't have any element with the id you are looking for, the final result will be an error because in this line:

if (x.style.display === 'none') {

you will check for a value of X, but X is equals null because no element was returned. To fix this, replace the div in var x = document.getElementById(div) for the id you want. Remember that you should pass a string to the function, so even if the id was really div, it shoul go between quotes, like .getElementById("div");

Second, you never hided your divs! When you start your code you need to be sure to hide them before anything else. One way to do this is with CSS, but since you did not provide any CSS code, I will do it here with JavaScript since it's possible too:

var hideDIV = document.getElementById("myDIV");
var hideDIV2 = document.getElementById("myDIV2");
var hideDIV2A = document.getElementById("myDIV2A");

hideDIV.style.display = "none";
hideDIV2.style.display = "none";
hideDIV2A.style.display = "none";

Now we have all the divs hidden! They will start showing up when you click the proper links.

Finally, we have a code that works for the first state and the first city of that state. Simply replicate the logic for the other divs and you should be good to go :D

Full code working here:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>

  <body>

  <p><b>Click on links below to find the mayor of your city</b></p>

  <p id="demo" onclick="myFunction('myDIV')">States</p>
  <div id="myDIV">
    <p><b> Select a State</b></p>
    <p id="demo" onclick="myFunction('myDIV2')">Alabama</p>
    <p id="demo" onclick="myFunction(myDIV3')">Texas</p>
    <p id="demo" onclick="myFunction(myDIV4')">California</p>
  </div>

  <div id="myDIV2">
    <p><b>Select a City</b></p>
    <p id="demo" onclick="myFunction('myDIV2A')">Birmingham</p>
    <p id="demo" onclick="myFunction('myDIV2B')">Auburn</p>
    <p id="demo" onclick="myFunction('myDIV2C')">Montgomery</p>
  </div>

  <div id="myDIV2A">
    <p><b>The mayor of Birmingham Alabama is William Bell</b></p>
  </div>

  <script type="text/javascript">
  var hideDIV = document.getElementById("myDIV");
  var hideDIV2 = document.getElementById("myDIV2");
  var hideDIV2A = document.getElementById("myDIV2A");

  hideDIV.style.display = "none";
  hideDIV2.style.display = "none";
  hideDIV2A.style.display = "none";

  function myFunction(div) {
  var x = document.getElementById(div);
  if (x.style.display === 'none') {
    x.style.display = 'block';
  } else {
    x.style.display = 'none';
  }
  }
  </script>

  </body>

</html>

Upvotes: 0

Travis Acton
Travis Acton

Reputation: 4440

I would not recommend doing it this way but it seems you are in the early stages of learning so I will roll with it.

Let me preface this with your html is not valid, you have repeating IDs for elements, please fix that.

In the demo I provided, we add an initial class called "initialHide" and in our css file we set that to displey: none. This will initially tuck away all your cascading options.

We then change your onclick call to take in 2 params because not only do we need to know what we are targetting to display but all the sub options that need to be hidden when a user makes a choice. Ex: If a user changes the state then we need to hide the cities from the last choice and the mayor from the last choice. If a user changes only a city then we just need to hide the mayor from the last choice.

We will add a descriptive classname to parent divs so our js can target those elements. When the js is called we will then decide what we need to hide, select an array of elements by class name, iterate through and hide them. Then we will show our targeted choice after.

            function myFunction(div, hide) {
                if (hide === "state") {
                    var cities = document.getElementsByClassName("city");
                    for (var i = 0; i < cities.length; i++) {
                        cities[i].style.display = "none";
                    }
                    var mayors = document.getElementsByClassName("mayor");
                    for (var i = 0; i < mayors.length; i++) {
                        mayors[i].style.display = "none";
                    }
                } else {
                    var mayors = document.getElementsByClassName("mayor");
                    for (var i = 0; i < mayors.length; i++) {
                        mayors[i].style.display = "none";
                    }
                }
                var x = document.getElementById(div);
                if (x.style.display = 'none') {
                    x.style.display = 'block';
                } else {
                    x.style.display = 'none';
                }
            }
.initialHide {display:none;}
<p><b>Click on links below to find the mayor of your city</b></p>

        <p id="demo">States</p>
        <div id="myDIV">
            <p><b> Select a State</b></p>
            <p id="demo1" onclick="myFunction('myDIV2', 'state')">Alabama</p>
            <p id="demo2" onclick="myFunction('myDIV3', 'state')">Texas</p>
            <p id="demo3" onclick="myFunction('myDIV4', 'state')">Tenneessee</p>
        </div>
        <div id="myDIV2" class="initialHide city">
            <p><b>Select a City</b></p>
            <p id="demo4" onclick="myFunction('myDIV2A', 'city')">Birmingham</p>
            <p id="demo5" onclick="myFunction('myDIV2B', 'city')">Auburn</p>
            <p id="demo6" onclick="myFunction('myDIV2C', 'city')">Montgomery</p>
        </div>
        <div id="myDIV3" class="initialHide city">
            <p><b>Select a City</b></p>
            <p id="demo7" onclick="myFunction('myDIV3A', 'city')">Dallas</p>
            <p id="demo8" onclick="myFunction('myDIV3B', 'city')">Houston</p>
            <p id="demo9" onclick="myFunction('myDIV3C', 'city')">Austin</p>
        </div>
        <div id="myDIV4" class="initialHide city">
            <p><b>Select a City</b></p>
            <p id="demo10" onclick="myFunction('myDIV4A', 'city')">Memphis</p>
            <p id="demo11" onclick="myFunction('myDIV4B', 'city')">Nashville</p>
            <p id="demo12" onclick="myFunction('myDIV4C', 'city')">Knoxville</p>
        </div>

        <div id="myDIV2A" class="initialHide mayor">
            <p><b>The mayor of Birmingham Alabama is William Bell</b></p>
        </div>
        <div id="myDIV2B" class="initialHide mayor">
            <p><b>The mayor of Auburn Alabama is Smitty McSmitt</b></p>
        </div>
        <div id="myDIV2C" class="initialHide mayor">
            <p><b>The mayor of Montgomery Alabama is Monty McMontFace</b></p>
        </div>

        <div id="myDIV3A" class="initialHide mayor">
            <p><b>The mayor of Dallas TX is awdeqdweqd</b></p>
        </div>
        <div id="myDIV3B" class="initialHide mayor">
            <p><b>The mayor of Houston TX is awdeqdweqvswwsd</b></p>
        </div>
        <div id="myDIV3C" class="initialHide mayor">
            <p><b>The mayor of Austin TX is Monty McMontFace</b></p>
        </div>

        <div id="myDIV4A" class="initialHide mayor">
            <p><b>The mayor of Memphis TN is William Bell</b></p>
        </div>
        <div id="myDIV4B" class="initialHide mayor">
            <p><b>The mayor of Nashville TN is Smitty McSmitt</b></p>
        </div>
        <div id="myDIV4C" class="initialHide mayor">
            <p><b>The mayor of Knoxville TN is Monty McMontFace</b></p>
        </div>

Upvotes: 0

Veracity
Veracity

Reputation: 49

I could write code for you that you can just use for this, but I think your goal is to learn how to do this on your own, so Im going to try to explain what is happening in this type of code, and hopefully give you the understanding that you seem to be lacking in order to make this type of code. First off, a class is what you can have many of and id is what you can only have one of.

Your code have an id=demo on many lines, and that is not something you can do. You must use a class if you have many of it. Id is for selecting one specific item from the rest, so id must always be unique. But you only need to give the item an id when you need to select that specific item from somewhere in your code later on.

var myDiv = selectElementById("myUniqueDiv"); 

The code on the live above will select a spesific div with a spesific Id. The myDiv variable kind of hold that div now.

If I say:

var allDivs = selectElemetnsByClassName("myDivs");

i can select all divs with a specific class name. the allDivs variable holds sort of like a list of all those elements that i have selected.

Elements can belong to one or more clases, but only one element can use a specific id.

When you are selecting elements inside other elements, like all paragraphs inside of a div, you can make variables and store first the main div, then you use that variable (that holds all elements it it) to select further from what is inside of it.

var citys = document.getElementById('citys'); // select main div
citys.getElementsByTagName("p"); // selecting all p elements in it

You can then set it to display or not. First you can sett all the elements to be hidden, then you can display only the one of them that is clicked on.

citys.style.display = "none"; 

The line above hides all p selected from the city div.

function myFunction(selectedCity){
    document.getElementsById( selectedCity ).style.display = "block";

}

These last line uses id to select a specific city and makes it visible. What you have in the parenthesis in the myFunction() declaration, here i have selectedCity, becomes a variable that holds what you have give it when you called the function. I use that to select the city I want to display.

Suggestion: I would use drop downs lists for this, in stead of hiding and un-hiding elements.

I hope this explains your code enough for you to understand how to write this type of code on your own.

Upvotes: 2

sanjiv saini
sanjiv saini

Reputation: 356

You have not hidden the div, so how does it going to be hidden.

You can do any one of the two things:

  1. write CSS to hide the element initially. Writing this style property inside head tag, will do the job.

    <style>
      #myDIV, #myDIV2, #myDIV2A{
        display: none;
      }
    </style>
  2. You can call the function as soon as you declare it, with the ids of div you want to hide

    <script>
    
    
    function myFunction(div) {
      var x = document.getElementById(div);
      if (x.style.display === 'none') {
        x.style.display = 'block';
      } else {
        x.style.display = 'none';
      }
    }
    
    myFunction('myDIV');
    myFunction('myDIV2');
    myFunction('myDIV2A');
    
    </script>

Upvotes: 0

Related Questions