You need popular dynamically select
of cities. For this you can use Ajax with pure JavaScript or jQuery.
It works as follows: when selecting a State, the script will send the state code to a PHP page, and this page will make the request to the database of all cities with the State code received, then return an HTML with options
that will be inserted in select
of cities.
I'll give you a basic example using jQuery, which gets easier, and you can apply it in your code with ease:
Capture value
of select
of States when selected and call Ajax:
$("#estado").on("change", function(){
var id_estado = $(this).val();
$.ajax({
url: 'cidades.php',
data: { estado: id_estado }
dataType: 'html',
complete: function(result) {
$("#cidade").html(result);
}
});
});
In Ajax above, I send id
of the selected state to a PHP page called cidades.php
(you can use whatever name you want). This cidades.php
page will be responsible for returning to the list of cities in the selected state. This page should contain nothing but PHP codes and the construction of options
that will be inserted in select
of cities. It is not an ordinary page, with <html><head><body>
etc ...
Page cidades.php
:
As stated, the only utility on this page is to return options
to select
cities.
The layout of this page would be:
<?php
$estado = $_GET['estado']; // recebendo o id do Estado enviado pelo Ajax
if(isset($estado) && !empty($estado)){
// FAZER A REQUISIÇÃO AO BANCO DE DADOS USANDO A VARIÁVEL
// $estado PARA PEGAR APENAS AS CIDADES COM ESSE id
// AQUI FAZER UM LOOP NOS RESULTADOS
while(ENQUANTO HOUVER RESULTADO VINDO DO BANCO){
echo "<option value='$ID_DA_CIDADE'>$NOME_DA_CIDADE</option>";
}
}
?>
To call cities on page load, as the first state in select
is already selected, you can use jQuery below, which triggers a trigger in select
:
$(window).on("load", function(){
$("#estado").trigger("change");
});
Do not forget to load jQuery into your <head>
. You can use this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
SothefulljQueryscriptwouldlooklike:
<script>$("#estado").on("change", function(){
var id_estado = $(this).val();
$.ajax({
url: 'cidades.php',
data: { estado: id_estado }
dataType: 'html',
complete: function(result) {
$("#cidade").append(result);
}
});
});
$(window).on("load", function(){
$("#estado").trigger("change");
});
</script>