Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display divs based on selected option inside the selector with many options

I have a #selector selector with a huge number of options. At different times, the number of options can reach several dozen.

When the page loads, I display the #a div next to the selector.

I need to make it so that when other options are selected, the rest of the divs are hidden and only the specific one is displayed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example, when the user selects the "C" option, a div with #c ID should be displayed. Etc.

I used the script below but don’t understand why it doesn’t work.

I would appreciate valuable advice.

function valueNew(ele) {
  var div = document.getElementsByClassName('block');
  // iterating over them and hidding all
  for( var i=0;i<div.length;i++) {
    div[i].style.display = 'none'
  }
  div[ele.value].style.display = 'block';
}
// trigger change event to show default div
document.getElementById('selector').onchange();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selector">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
  <option value="4">D</option>
  <option value="5">E</option>
  <option value="6">F</option>
  <option value="7">G</option>
</select>

<!-- This div is displayed by default on page load. -->
<div id="#a" class="block" style="display: none;">Content for the A option</div>

<div id="#b" class="block" style="display: none;">Content for the B option</div>
<div id="#c" class="block" style="display: none;">Content for the C option</div>
<div id="#d" class="block" style="display: none;">Content for the D option</div>
<div id="#e" class="block" style="display: none;">Content for the E option</div>
<div id="#f" class="block" style="display: none;">Content for the F option</div>
<div id="#g" class="block" style="display: none;">Content for the G option</div>

>Solution :

It’s because of the () you placed after the .onchange take them away, and instead tell the program which function you want to call by placing it there without calling it-

document.getElementById("selector").onchange = valueNew;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading