esedic
9/9/2014 - 6:17 AM

jQuery Cascading Dropdown

jQuery Cascading Dropdown

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>jQuery Cascading Dropdown</title>
    <script type='text/javascript' src='//code.jquery.com/jquery-1.10.1.js'></script>
</head>
<body>
  <label class="page1">Country</label>
<div class="tooltips" title="Please select the country that the customer will primarily be served from">
    <select id="country" name="country" placeholder="Phantasyland">
        <option></option>
        <option>Germany</option>
        <option>Spain</option>
        <option>Hungary</option>
        <option>USA</option>
        <option>Mexico</option>
        <option>South Africa</option>
        <option>China</option>
        <option>Russia</option>
    </select>
</div>
<br />
<br />
<label class="page1">Location</label>
<div class="tooltips" title="Please select the city that the customer is primarily to be served from.">
    <select id="location" name="location" placeholder="Anycity"></select>
</div>

<script type='text/javascript'> 
jQuery(function($) {
    var locations = {
        'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
        'Spain': ['Barcelona'],
        'Hungary': ['Pecs'],
        'USA': ['Downers Grove'],
        'Mexico': ['Puebla'],
        'South Africa': ['Midrand'],
        'China': ['Beijing'],
        'Russia': ['St. Petersburg'],
    }
    
    var $locations = $('#location');
    $('#country').change(function () {
        var country = $(this).val(), lcns = locations[country] || [];
        
        var html = $.map(lcns, function(lcn){
            return '<option value="' + lcn + '">' + lcn + '</option>'
        }).join('');
        $locations.html(html)
    });
});
</script>
</body>
</html>