I am trying to make a form with several drop downs for selecting location in the world.
<div class="form-group control-group">
<label for="text" class="col-sm-2 control-label">Country</label>
<div class="col-sm-8">
<select class="form-control">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
</div>
<div class="form-group control-group">
<label for="text" class="col-sm-2 control-label">State/Province</label>
<div class="col-sm-8">
<select class="form-control">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
</div>
<div class="form-group control-group">
<label for="text" class="col-sm-2 control-label">City</label>
<div class="col-sm-8">
<select class="form-control">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
</div>
<div class="form-group control-group">
<label for="text" class="col-sm-2 control-label">Postal Code</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="subject" name="subject">
</div>
</div>
I want to display only the country list if country is not selected and country and state/province list if country is selected... so on. The list will be stored in SQL.
Any help is appreciated. Thanks.
<select id="country" class="form-control" onchange="javascript:countryChange();">
<option>1</option>
<option>2</option>
</select>
<select id="state" class="form-control" onchange="javascript:stateChange();">
</select>
<select id="city" class="form-control"></select>
<script>
function countryChange() {
var selected = jQuery("#country option:selected").text();
jQuery.ajax({
url: "country2states.php?country="+selected
}).done(function(msg) {
jQuery("#state").html('');
jQuery("#city").html('');
jQuery("#state").html(msg);
});
}
function stateChange() {
var selected = jQuery("#state option:selected").text();
jQuery.ajax({
url: "state2cities.php?state="+selected
}).done(function(msg) {
jQuery("#city").html('');
jQuery("#city").html(msg);
});
}
</script>
For the first function to work, you have to create a PHP page (country2states.php) to handle the database query to retrieve the list of states for the selected country
"SELECT statename FROM states WHERE country='" . $_GET['country'] . "';"
and return it ECHOing a string formatted like this:
"<option>Iowa</option><option>South Dakota</option><option>Texas</option>....."
Same stuff for the second function, you will create state2cities.php and you know the rest. :)