简体   繁体   中英

Dropdown option changes based on max number and other dropdown selection

I have a page with 2 dropdown boxes. One is used for picking a number of adults, the other is for the number of children.

The total combined max of the selection can not be higher than 10. So if for example pick 4 in adults the number of options in the children dropdown will be 0 to 6. If I pick 9 in adults the options in the children dropdown will only be 0 and 1. THe total combined selection can never get above 10.

I am fairly new to JS/jQuery. Can anyone give me tips or point me in the right direction?

/Michael

You can do something like this:

  $(document).ready(function () { $("#ddlAdult").change(function(){ console.log("In"); var value = parseInt($(this).val()); var optionsToBeCreated = 10 - value; var count =0; $("#ddlChildren").empty(); console.log(optionsToBeCreated); while(count <= optionsToBeCreated) { console.log("In"); $("#ddlChildren").append("<option value="+count+">"+count+"</option"); count = count + 1; } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="ddlAdult"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> <select id="ddlChildren"> </select> 

Save the code below in HTML and run in browser. This will work as you expected.

 <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script language="javascript"> var adultValue=0; var childValue=0; var valueChk=0; $( document ).ready(function() { for(i=0;i<=10;i++) $(".adult").append('<option value='+i+'>'+i+'</option>'); $( ".adult" ).change(function() { adultValue=$( ".adult" ).val(); // alert(adultValue); valueChk=10-adultValue; $('.child') .find('option') .remove() .end(); for(j=0;j<=valueChk;j++) { $(".child").append('<option value='+j+'>'+j+'</option>'); } }); $( ".child" ).change(function() { valueChk=parseInt($( ".adult" ).val())+parseInt($( ".child" ).val()); alert(valueChk); }); }); </script> </head> <body> <select class="adult"> </select> <select class="child"> </select> </body> </html> 

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