简体   繁体   中英

How to reset default value in an select based on previous select tag?

I have two select options :

<select id="Living things">
<option>Choose Any</option>
<option>Animals</option>
<option>Plants</option>
</select>

<select id="Compare">
<option>Any</option>
<option>less</option>
<option>greater</option>
</select>

Consider the first options from both the drop downs are default. Now imagine I selected 'Animals' from first and 'less' from second. Now if I change the first to 'Plants' then the second list should be reset.ie,

<option>Any</option>
<option>less</option>
<option>greater</option>

Please help in this.Thank You.

<select id="livingThings" onchange="reset();">
<option>Choose Any</option>
<option>Animals</option>
<option>Plants</option>
</select>

<select id="compare">
<option>Any</option>
<option>less</option>
<option>greater</option>
</select>
<script src="test.js"></script>

livingThings = document.getElementById('livingThings');
compare =document.getElementById('compare');

function reset(){
if (livingThings.selectedIndex != 0){
compare.selectedIndex = 0;
}
}

You can add an event listener for the first select element whenver it changes then reset the value of the second select element to its default, note that IDs can not have white spaces, I have added a dash to it

 document.querySelector("#Living-things").onchange = function() { let select = document.querySelector("#Compare"); select.value = select.children[0].value; }
 <select id="Living-things"> <option>Choose Any</option> <option>Animals</option> <option>Plants</option> </select> <select id="Compare"> <option>Any</option> <option>less</option> <option>greater</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