Billy Logan
Billy Logan

Reputation: 2520

How to display a select only when other select's option was chosen?

I have 4 selects on a page and only the first one is visible. Also, the first select has basic prompt string: Choose person like this:

<select name="post[person_id]">
  <option value="">Choose person</option>
  <option value="1">David</option>
  <option value="2">Sam</option>
  <option value="3">Tobias</option>
</select>

Once user chooses some option from the first dropdown, the other 3 selects have to be displayed.

How to implement it?

Upvotes: 0

Views: 1500

Answers (2)

mwilson
mwilson

Reputation: 12900

Here is a simple jquery solution. The key is to use the .change event and hook it up to your dropdown(s).

HTML

    <select id="controllerDD">
        <option value="">Select...</option>
        <option value="Show 1">Show 1</option>
        <option value="Show 2">Show 2</option>
        <option value="Show All">Show All</option>
    </select>
    <p>DD 1</p>
    <select id="DD1" style="display:none">
        <option value="blah">Select...</option>
        <option value="blah">blah</option>
        <option value="blah">blah</option>
        <option value="blah">blah</option>
    </select>
    <p>DD 2</p>
    <select id="DD2" style="display:none">
        <option value="blah">Select...</option>
        <option value="blah">blah</option>
        <option value="blah">blah</option>
        <option value="blah">blah</option>
    </select>

JavaScript

$('#controllerDD').change(function (e) {
    var selected = $(e.currentTarget).val();
    $('#DD1').hide();
    $('#DD2').hide();
    switch (selected) {
        case "Show 1":
            $('#DD1').show();
            break;
        case "Show 2":
            $('#DD2').show();
            break;
        case "Show All":
            $('#DD1').show();
            $('#DD2').show();
            break;
        default:
            break;
    }
})

Upvotes: 2

Alvaro Silvino
Alvaro Silvino

Reputation: 9743

You have to use onchange methods.

<select onchange="myFunction()">

<script>
function myFunction(){

// fetch new data for the next select. 

//append the new options on next select. 

// make select available or enabled 

}

</script>

For the first select use the onchange to fetch (populate) the options of the next selects. And do the same for the following selects.

You can also fetch and make it available in the instance you finish to populate the select.

In case you are not using jQuery. You can append the option

Upvotes: 1

Related Questions