简体   繁体   中英

jquery php code to bind state and city from mysql database table

I have a form where in one table row a dropdown state field is there and in another tr another dropdown is there for selecting city, I need that before submitting the form when user selects a state from dropdown list automatically the city dropdown should fetch and display only those city from the selected state.

I don't want to use AJAX but want to do it with jquery. Backend database has two tables one is state with two fields id and state, second is city table having 3 fields id, state and city where state is my foreign key.

How can I do it with jquery any help regarding this will be appreciated since I am a newbie, please help

If you don't want to use ajax you can always preload the full list of states with cities into a javascript object and call it from there.

Example:

<select id="stateDrop">
    <option value="state1">State 1</option>
    <option value="state2">State 2</option>
</select>
<select id="cityDrop"></select>
    <script>
    var cities = {'state1':['city_one', 'city_two', 'city_three'], 'state2':['city_four', 'city_five', 'city_six']};
    $('#stateDrop').on('change', function(){
        var cityList = cities[$(this).val()];
        console.log(cityList);
        var output = '';
        $(cityList).each(function(k, v){
            output += '<option value="'+v+'">'+v+'</option>';
        });
        $('#cityDrop').html(output);
    });
    </script>

Fiddle

If you want to avoid using an ajax call, you will need to build a mapping from state-id's to lists of cities. Then bind a function to the change event of the state select-element, and populate the city select-element with the values.

Assuming State ID 0 has the cities A and B, with city id's 0 and 1:

var map = [[{id:0,name:"A"},{id:1,name:"B"}]]            
$("#states").on("change",function() {
    var cities = map[$(this).val()];
    $("#cities option").remove(); //remove previous options
    $.each(cities, function(i,e) {
        $("#cities").append('<option value="'+e.id+'">'+e.name+'</option>');
    });
});

Example: http://jsfiddle.net/HQLQU/

The php/mysql part for building the JS-map could be something like this (untested!):

$query = "SELECT city_id, city_name, state_id FROM cities";
$result = mysql_query($query); //or preferably use a more modern extension
$cities = array();
foreach (mysql_fetch_assoc($result) as $row) {
    $cities[$row['state_id']][] = array("id"=>$row['city_id'],"name"=>$row['city_name']);
}
echo "var map = " . json_encode($cities);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM