Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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>