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.
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" style="display: none;">Content for the A option</div>
<div id="#b" style="display: none;">Content for the B option</div>
<div id="#c" style="display: none;">Content for the C option</div>
<div id="#d" style="display: none;">Content for the D option</div>
<div id="#e" style="display: none;">Content for the E option</div>
<div id="#f" style="display: none;">Content for the F option</div>
<div id="#g" style="display: none;">Content for the G option</div>
CodePudding user response:
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;