Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Prince Sargbah
Prince Sargbah
2,551 Points

How to populate two select dropdown menus using Ajax

I'm creating two dropdown fields from 2 two tables in my database (States and Cities). The Cities tables are linked to each states. I converted the data from both tables to Json using php. I use Ajax to populate both select dropdown as well. Now, I want to filter the cities dropdown when a user select a state from the state dropdown. I'm using the code below and it's working fine, except, it's adding one empty option field after each populated option fields. Any help?

<script>

function State() {
    $('#statedd1').empty();
    $('#statedd1').append("<option value='0'>- Select State -</option>");
    $('#citydd1').append("<option value='0'>- Select City -</option>");
    $.ajax({
        type:"GET",
        url:"states.php",
        contentType:"application/json; charset=utf-8",
        dataType:"json",
        success: function(data) {
            $('#statedd1').empty();
            $('#statedd1').append("<option value='0'>- Select Company -</option>");
            $.each(data,function (index, item) {
                $('#statedd1').append('<option value="'+ item.State_ID +'">'+ item.State_Name +'<option>');
            });
        },complete: function() {}
    });
}

function City(State_ID) {
    $('#citydd1').empty();
    $('#citydd1').append("<option>Loading...</option>");
    $.ajax({
        type:"GET",
        url:"cities.php?Id="+State_ID,
        contentType:"application/json; charset=utf-8",
        dataType:"json",
        success: function(data) {
            $('#storedd1').empty();
            $('#storedd1').append("<option value='0'>- Select Store -</option>");
            $.each(data,function (index, item) {
                $('#citydd1').append('<option value="'+ item.CityID +'">'+ item.CityName +'<option>');
            });
        },complete: function() {}
    });
}

$(document).ready(function() {
        State();
        $("#statedd1").change(function() {
            var State_ID = $("#statedd1").val();
            City(State_ID);
        });
    });

</script> </head>

<body> <br><br> <p> <select id="statedd1"></select> </p> <br><br> <p><select id="citydd1" multiple></select></p>

</body> </html>