简体   繁体   中英

Show/hide section based on option value without using jQuery

i need to show/hide different div based on the selected option of a dropdown menu. I've tried all the solutions explained in the previous tickets. When they use jQuery libraries, the show/hide action works, but they get in conflict with other page elements (ex. image sliders and counter bar are hidden). All the others solutions don't work, despite the one explained in this ticket ( How can I show a hidden div when a select option is selected? ). It works well, but only with two values. I need to extend this method to more than two values.

i write here the working code.

 function showDiv(divId, element) { document.getElementById(divId).style.display = element.value == 1 ? 'block' : 'none'; }
 #hidden_div { display: none; }
 <select id="test" name="form_select" onchange="showDiv('hidden_div', this)"> <option value="0">No</option> <option value="1">Yes</option> </select> <div id="hidden_div">This is a hidden div</div>

PS: I'm not an expert in javascript. Thanks again.

I have modified the solution you referred to and it seems to be working (if I understand your question correctly):

HTML:

<select id="test" name="form_select" onchange="showDiv(this)">
   <option value="hidden_div1">Show div 1</option>
   <option value="hidden_div2">Show div 2</option>
   <option value="hidden_div3">Show div 3</option>
   <option value="hidden_div4">Show div 4</option>
</select>

<div id="hidden_div1">This is hidden div 1</div>
<div id="hidden_div2">This is hidden div 2</div>
<div id="hidden_div3">This is hidden div 3</div>
<div id="hidden_div4">This is hidden div 4</div>

CSS:

div[id*="hidden_div"] {
  display: none;
}

javascript:

// When the page loads, make sure the already selected div is shown.
window.onload = function afterPageIsLoaded() {
    showDiv();
}

function showDiv(element) {
    // Create an array of all the hidden divs elements.
    const hiddenDivs = [...document.querySelectorAll("div[id*='hidden_div']")];

    // Loop over them and hide every one of them.
    hiddenDivs.map(hiddenDiv => hiddenDiv.style.display = 'none');

    // Get the selected id from the select.
    const id = document.getElementById('test').value;

    // Get the selected div and display it.
    document.getElementById(id).style.display = 'block';
}

Link to the jsFiddle: https://jsfiddle.net/1jpad5x4/

If I misinterpreted your question or something is not clear, let me know!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM