简体   繁体   中英

How i can show a select list only after another select (parent) has been selected

Like i said in the title i want to keep a list hidden until another another list above has been selected, for example show student list after a class had been selected (so only student who belong to the selected class are shown)

<select name="class">
   <option value="">class1</option>
   <option value="">class2</option>
</select>

<select name="student">
  <option value="">student1</option>
  <option value="">student2</option>
</select>

Initially apply a hidden class (with display: none styling) to the second select list and then on the change of value (indicating a choice has been made) in the first select - remove the hidden class.

EDIT - as as suggested by @HerrSerker - the event listener is now in the JS as opposed to inline in the HTML.

Note that each select list has a selected disabled option - to allow for a blank option rather than the first option selected by default.

 // add event listener for change of class select list document.querySelector('select[name="class"]') .addEventListener('change', updateStudent) //function to remove the hidden class and styling of the second select list function updateStudent() { var el = document.querySelector('select[name="student"].hidden'); el.classList.remove('hidden') } 
 select[name="student"].hidden { display:none } 
 <select name="class"> <option disabled selected></option> <option value="">class1</option> <option value="">class2</option> </select> <select name="student" class="hidden"> <option disabled selected></option> <option value="">student1</option> <option value="">student2</option> </select> 

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