Change select element value (Ajax + php) with innerHTML

Question:

Hi, I'm doing the famous combo of state loads city. Everything is working perfectly, as I debugged in my script, until the moment it should change the value of the select (options returned from the function). Here's my code (index.php):

<div class="form-group">
    <label class="col-md-4 control-label col-xs-12" for="Endereco">Endereço*</label>
    <div class="col-md-1 col-xs-4">
        <select class="selectpicker" data-width="auto" id="estado" name="estado">
    <?php
            $query = "SELECT SIGLA, CODIGO FROM estado ORDER BY TX_SIGLA";
            $result = mysqli_query($conectar, $query);
            while ($resultado = mysqli_fetch_assoc($result)) { ?>
                <option value="<?php echo $resultado['CODIGO']; ?>"><?php echo $resultado['SIGLA']; ?></option>
    <?php   } ?>  

        </select>
    </div>    

    <div class="col-md-3  col-xs-4">
        <select data-width="auto" id="municipio" name="municipio" class="selectpicker">
            <option value="0" disabled="disabled">Escolha o estado</option>
        </select>
    </div>
</div>

Code (city.php):

<?php
if (isset($_POST["cd_estado"])) {

    $cod_estado = $_POST["cd_estado"];
    $query = "SELECT NOME, CODIGO FROM municipio WHERE ESTADO = '$cod_estado' ORDER BY NOME";
    $result = mysqli_query($conectar, $query);

    while ($resultado = mysqli_fetch_assoc($result)) {
        echo '<option value="' . $resultado['CODIGO'] . '">' . $resultado['NOME'] . '</option>';
    }
} else {
    echo "<option value='0'> Sem cidade </option>";
}
?>

Script:

<script>
$(document).ready(function() {

    $("#estado").change(function() {

        $("#municipio").html('<option value="0">Carregando...</option>');

        var est = document.getElementById("estado").value;

        $.ajax({
            type: 'post',
            url: 'cidade.php',
            data: {
                cd_estado: est
            },
            success: function(data) {
                document.getElementById("municipio").innerHTML = data;
                console.log(data);
            }
        });

    });
});
</script>

I've already tried to change the value of the select "municipio" with the following alternatives:

$("#municipio").html(data);
$("#municipio").append(data);
document.getElementById("municipio").innerHTML = data;
$("select[name=municipio]").html(data);

None work. But in the "console.log(data);" the value is being returned correctly. What am I doing wrong?

Answer:

To insert options in your select do as follows:

municipios = document.getElementById('municipio');

municipios.options[municipios.options.length] = new Option('Texto', 'Valor');

and to reset the values ​​just use:

municipios.options.length = 0;
Scroll to Top