Skip to content
Advertisement

show/hide section in wordpress with select values

I use Divi Theme in WordPress. I have sections that I gave IDs. I have a select, and for each option value I use the sections IDs. I want show one section by changing the select option and hide the other section that is showed.

Here is the select :

<select name="years" id="mySelect" onchange="myFunction()">
      <option value="">TOUTES LES ANNÉES </option>
      <option value="section2020">2020</option>
      <option value="section2019">2019</option>
      <option value="section2018">2018</option>
      <option value="section2017">2017</option>
      <option value="section2016">2016</option>
      <option value="section2015">2015</option>
</select>

Here is the javascript :

<script>
function myFunction() {
  var x = document.getElementById("mySelect").value;
  if (x.style === "display:none;") {
    x.style = "display:block";
  } else {
    x.style = "display:none;";
  }
}
</script>

Could you tell my why it’s not working ?

thanks Caroline

Advertisement

Answer

In your code, you are trying to style a string value x.style

If we see closely var x = document.getElementById("mySelect").value; this is returning a string value not an html element. But yes we can use this string value to get html element and make it visible and hide other.

  function myFunction() {
    var selectElement = document.getElementById("mySelect"); 
    var selectedValue = selectElement.value;
    var selectedElement = document.getElementById(selectedValue);
          
    if (selectedElement.style.display === "none") {
       var elements = document.getElementsByClassName('section');
       for(var i = 0; i < elements.length; i++){
	      elements[i].style.display = "none";
       }
       selectedElement.style.display = "block";
    } 
    else {
            selectedElement.style.display = "none";
         }
}
        <select name="years" id="mySelect" onchange="myFunction()">
              <option value="">TOUTES LES ANNÉES </option>
              <option value="section2020">2020</option>
              <option value="section2019">2019</option>
              <option value="section2018">2018</option>
              <option value="section2017">2017</option>
              <option value="section2016">2016</option>
              <option value="section2015">2015</option>
        </select>


    <div id="section2020" class='section' style='display:none'><h1>2020</h1></div>
    <div id="section2019" class='section' style='display:none'><h1>2019</h1></div>
    <div id="section2018" class='section' style='display:none'><h1>2018</h1></div>
    <div id="section2017" class='section' style='display:none'><h1>2017</h1></div>
    <div id="section2016" class='section' style='display:none'><h1>2016</h1></div>
    <div id="section2015" class='section' style='display:none'><h1>2015</h1></div>


        
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement