vassilis ntovantzis
vassilis ntovantzis

Reputation: 352

How to expand options in a select in the same option/dropdown menu

I want to create a select menu with a drop down list. But because there are a lot of choices I would like to show them categorized. Let's say I need people to select city. I would like countries and cities be an option, but if I select a country then the options expands in the cities of the selected country. Generally in html I can easily do but in the form it is a little bit tricky..

Here is my html code:

<select class="" placeholder="Your Choice">
    <option value="Your Destination">Country1</option>
    <option value="Your Destination">city1</option>
    <option value="Your Destination">city2</option>
    <option value="Your Destination">city3</option>
    <option value="Your Destination">Country2</option>
    <option value="Your Destination">city1</option>
    <option value="Your Destination">city2</option>
    <option value="Your Destination">city3</option>
</select>

Upvotes: 2

Views: 1726

Answers (1)

Rajesh
Rajesh

Reputation: 24925

This is not the best implementation, but can be used as reference for start.

JSFiddle

Code

function createCountries() {
    var html = "";
    for (var i = 0; i < 5; i++) {
        html += "<div class='country'>Country " + i + "</div>";
        html += "<div class='cities'></div>";
    }
    $("#content").html(html)
}

function createCities() {
    $(".country").each(function (row) {
        var random = Math.floor(Math.random() * 10)
        var html = "";
        console.log(random);
        if (random == 0) random = 5;

        for (var i = 0; i < random; i++) {
            html += "<div href='#' class='city'>City " + i + "</div>";
        }
        $(this).next().html(html);
    })
}

function createAccordions() {
    $("#content").accordion({
        collapsible: true,
        autoHeight: false,
        active: 100                 // Hack to keep it closd default
    });
    $("#main").accordion({
        collapsible: true,
        autoHeight: true,
        active: 100                 // Hack to keep it closd default
        
    });
}

function createHTML() {
    console.log($("#content").html())
    createCountries();
    createCities();
    createAccordions();
}

createHTML()
.country {
    color:#333;
    font-size:16px;
}
.city {
    color:Blue;
    font-size:14px;
    padding:5px;
    border-bottom:1px solid gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<div id="main">
    <div>Main</div>
    <div id="content"></div>
</div>

Upvotes: 1

Related Questions