Mejdi Dallel
Mejdi Dallel

Reputation: 632

JavaScript show and hide select list

i have a selection list that contains for example countries :

<select id="Countries" name="Countries" onChange="check();">
   <option id="Countrie1" name="Countrie1">Country 1</option>
   <option id="Countrie2" name="Countrie2">Country 2</option>
</select>

I want to use Javascript to hide and show another select list (Teams list) depending from the selected element of the countries select list.

For example if Country 1 is selected then show the teams' selection list of Country 1

<select id="Teams_Country_1" name="Teams_Country_1">
   <option id="C1_Team1" name="C1_Team1">Team_1_Country_1</option>
   <option id="C1_Team2" name="C1_Team2">Team_2_Country_1</option>
</select> 

if Country 2 is selected then hide the first one and show the second one in the same position.

<select id="Countries" name="Countries">
   <option id="C2_Team1" name="C2_Team1">Team_1_Country_2</option>
   <option id="C2_Team2" name="C2_Team2">Team_2_Country_2/option>
</select>

This is the code I am trying to modify to make it work.

function check() {
    var el = document.getElementById("Countries");
    var str = el.options[el.selectedIndex].text;
    if (str == "Countrie1") {
        showTeamsC1();
        hideTeamsC2();
    } else if (str == "Countrie2") {
        showTeamsC2();
        hideTeamsC1();
    }
}
function hideTeamsC1() {
    document.getElementById('Teams_Country_1').style.visibility = 'hidden';
}
function showTeamsC1() {
    document.getElementById('Teams_Country_1').style.visibility = 'visible';
}
function hideTeamsC2() {
    document.getElementById('Teams_Country_2').style.visibility = 'hidden';
}
function showTeamsC2() {
    document.getElementById('Teams_Country_2').style.visibility = 'visible';
}

But this dosen't show the select list in the same position, and if I do it manually (try to use margin-top) it covers the other list.

Upvotes: 0

Views: 114

Answers (1)

Amr Elgarhy
Amr Elgarhy

Reputation: 68902

You need to use display: none; instead of visibility:hidden; What is the difference between visibility:hidden and display:none?

Visibility hidden is hiding the element but keep its space, but display:none; hide it without keeping its space.

So your code will be something like this:

function hideTeamsC1() {
    document.getElementById('Teams_Country_1').style.display = 'none';
}
function showTeamsC1() {
    document.getElementById('Teams_Country_1').style.display = 'block';
}
function hideTeamsC2() {
    document.getElementById('Teams_Country_2').style.display = 'none';
}
function showTeamsC2() {
    document.getElementById('Teams_Country_2').style.display = 'block';
}

Upvotes: 2

Related Questions