Search code examples
javascriptjquerymathdropdownbox

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


Solution

  • 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>