show form-control only when value chosen on previous form-control with html and php

456 views Asked by At

I am creating a webpage with from-controls (2 in this exemple). My code is the following :

<body>

    <div class="option_choice_global">
         Select your options 

        <div class="col-xs-2">
            <label> Application </label>
            <select class="form-control" id="application">
                <?php 
                    $applications = get_apps(); 
                    foreach ($applications as $key => $value) { echo '<option value='.$key.'>'.$value.'</option>'; }
                ?> 
            </select>
        </div> 

        <div class="col-xs-1">
            <label> Version </label>
            <select class="form-control" id="version">
                <?php 
                    $versions = get_versions(); 
                    foreach ($versions as $key => $value) { echo '<option value='.$key.'>'.$value.'</option>'; }
                ?> 
            </select>
        </div> 

        <div class="col-xs-12">   
            <button type="submit" class="btn btn-default" onclick="fonction_submit_graph(this)">  <b> Submit </b>  </button>
        </div>                     
    </div>  

</body>

But I would like the second one (the version) to appear only when a value on the first controller (the application) is chosen. And my function get_versions() will then depend on the selected application : get_versions(application_number).

How can I do to show the second controller only when a value on the first one is selected ? And to get the selected value ? Thank you!

1

There are 1 answers

3
shalvah On BEST ANSWER

If I understand you right, you want to show the second select dropdown after a value is chosen from the first.

This can easily be done with JavaScript and CSS:

  • In the second select tag, add these attributes: style="{display: none;}". This will hide the dropdown. Also give it id="select2" for easy identification.
  • In the first select tag, add this attribute: onchange=showHiddenSelect(); This causes a function to be called when the value changes ie an option is selected. Also give it an id="select1".
  • Somewhere in your document, define the showHiddenSelect function like this: function showHiddenSelect() { document.getElementById("select2").style.display="block"; }

If you also wish to get the selected value, you'd just add this in that function: var select1value = document.getElementById("select1").value; and do what you want with it.

If you need the selected option from select1 to be sent to a backend and then used to calculate the options for select2, then your best bet would be to use AJAX to send and receive data from a script and then populate the select with JavaScript.