简体   繁体   中英

How can i reset a select box when i select an empty value of another select box using jquery?

I have two select boxes. How can i reset the second select box every time i select an empty value at the first select box using jquery? Here's the code:

 if( $('#regionId').val() ) { $('#cityId').val() } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <select name="regionId" id="regionId" aria-invalid="false" class="valid"> <option value="">Select a region...</option> <option selected="selected" value="4">California</option> <option value="3">New York</option> </select> <select name="cityId" id="cityId" aria-invalid="true" class="valid"> <option value="">Select a city...</option> <option selected="selected" value="5">Los Angeles</option> <option value="6">Miami</option> <option value="7" >New Jersey</option> </select> 

Use this code to make your city dropdown empty when the region is empty.

 function update(elem){ if($(elem).val() == ""){ $("#cityId").val("").change(); } } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <select name="regionId" id="regionId" aria-invalid="false" class="valid" onchange="update(this)"> <option value="">Select a region...</option> <option selected="selected" value="4">California</option> <option value="3">New York</option> </select> <select name="cityId" id="cityId" aria-invalid="true" class="valid"> <option value="">Select a city...</option> <option selected="selected" value="5">Los Angeles</option> <option value="6">Miami</option> <option value="7" >New Jersey</option> </select> 

You need to add an event handler for the changing of the #regionId control...

$(function() {
  $("#regionId").on("click", function() {
    ...
  });
});

You then need to check the value to see if it's empty... and if it is you need to set the empty value to #cityId ...

 $(function() { $("#regionId").on("click", function() { if($(this).val() == "") { $("#cityId").val("") } }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <select name="regionId" id="regionId" aria-invalid="false" class="valid"> <option value="">Select a region...</option> <option selected="selected" value="4">California</option> <option value="3">New York</option> </select> <select name="cityId" id="cityId" aria-invalid="true" class="valid"> <option value="">Select a city...</option> <option selected="selected" value="5">Los Angeles</option> <option value="6">Miami</option> <option value="7" >New Jersey</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