Combobox receive data in the second field (list menu)

0

Question: I have 2 Select Menu and I need the second select to change with data group according to the choice of the first one. Like for example car brand and models. In the first select the marks and in the second the models.

Testing: I have tried several formats of videos on Youtube and from here, I searched Google and some work but most do not work and even when I adapt to the problem I need to solve, it does not work.

What I have: Mysql with all information. Two tables, one table with only marks and the other table with 2 columns (make and model).

Last test: I tried to do a While to search, while the value of a select is equal to that of the other table, to display the records of the model of the second table, but only returns a blank value. The database connection is working because I test and return the result (by Dreamweaver) but in the list box menu does not show result. Command for Javascript that follows below:

<script type="text/javascript">
            function exiv() {
            var torinogv = document.getElementById("carrmarca").value;
            var seniorgv = document.getElementById("carrmodelo").value;

            var option = document.createElement("option");

                while (seniorgv == torinogv) {
                    option = document.getElementById("carrmodelo").text;
                    seniorgv.appendChild(option);
                }

            }
        </script>
    
asked by anonymous 05.05.2018 / 12:02

1 answer

0

Speak César Mattos!

So I understand, you want to make the famous "Cascade Combobox" , ie does one fill depend on the value selected in another?

If so, I have a simple solution using HTML, PHP, AJAX and MYSQL.

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Acesso - Petrovendas</title>
        <link href="src/css/bootstrap.css" rel="stylesheet" type="text/css"/>
        <link href="src/css/w3schools.css" rel="stylesheet" type="text/css"/>
        <link href="src/css/semantic.css" rel="stylesheet" type="text/css"/>
        <link href="src/css/styles.css" rel="stylesheet" type="text/css"/>
    </head>
    <body>
        <!-- Container -->
        <div class="w3-container">
            <form id="form_login" class="form-login w3-round w3-card-4" method="POST">
                <div id="logo" class="w3-center div-logo">
                    <img src="src/img/logo_carro.png" height="80px" class="img-logo"/>
                </div>
                <div class="form-group">
                    <select class="form-control" id="select-marca">
                        <option value="">Selecione uma marca...</option>
                    </select>
                </div>
                <div class="form-group">
                    <select class="form-control" id="select-modelo">
                        <option value="">Selecione um modelo...</option>
                    </select>
                </div>
                <br>
            </form>
        </div>
    </body>
    <script src="src/js/jquery-3.2.1.min.js" type="text/javascript"></script>

</html>

JAVASCRIPT WITH THE AJAX METHOD USING JQUERY:

/*
 * função executada ao carregar o DOM
 * lista todos os registros da tabela MARCA
 * via AJAX
 */
$(document).ready(function () {
    $.ajax({
        type: 'POST',
        dataType: 'JSON',
        url: 'processa-ajax.php?op=' + 'marca' + '&tabela=' + 'tbl_marca',
        success: function (dados) {
            $('#select-marca').empty();
            $("#select-marca").append('<option value="">Selecione uma marca...</option>');
            if (dados) {
                for (var i = 0; i < dados.length; i++) {
                    $("#select-marca").append("<option" + " value='" + dados[i].id + "'" + ">" + dados[i].marca + "</option>");
                }
            }
        }
    });
    $("#select-marca").val($("#select-marca option:first").val());
});

/*
 * função executa ao selecionar algum registro
 * no componente SELECT da MARCA.
 * preenche o SELECT dos com os modelos filtrados
 * na consulta via AJAX
 */
$("#select-marca").change(function () {
    var idMarca = $(this).val();
    $.ajax({
        type: 'POST',
        dataType: 'JSON',
        url: 'processa-ajax.php?op=' + 'modelo' + '&tabela=' + 'tbl_modelo' + '&id_marca=' + idMarca,

        success: function (dados) {
            $("#select-modelo").empty();
            $("#select-modelo").append('<option value="">Selecione um modelo...</option>');
            for (var i = 0; i < dados.length; i++) {
                $("#select-modelo").append("<option" + " value='" + dados[i].id + "'" + ">" + dados[i].modelo + "</option>");
            }
        }
    });
    $("#select-modelo").val($("#select-modelo option:first").val());
});

MY CSS STYLE

body{
    background: #eeeeee; /* Old browsers */
    background: -moz-radial-gradient(center, ellipse cover, #eeeeee 0%, #cccccc 100%); /* FF3.6-15 */
    background: -webkit-radial-gradient(center, ellipse cover, #eeeeee 0%,#cccccc 100%); /* Chrome10-25,Safari5.1-6 */
    background: radial-gradient(ellipse at center, #eeeeee 0%,#cccccc 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#eeeeee', endColorstr='#cccccc',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
}

.form-login{
    width: 350px;
    margin: 100px auto;
    padding: 15px 30px 10px 30px;
    background: rgb(238,238,238); /* Old browsers */
    background: -moz-radial-gradient(center, ellipse cover, rgba(238,238,238,1) 0%, rgba(238,238,238,1) 46%, rgba(234,234,234,1) 100%); /* FF3.6-15 */
    background: -webkit-radial-gradient(center, ellipse cover, rgba(238,238,238,1) 0%,rgba(238,238,238,1) 46%,rgba(234,234,234,1) 100%); /* Chrome10-25,Safari5.1-6 */
    background: radial-gradient(ellipse at center, rgba(238,238,238,1) 0%,rgba(238,238,238,1) 46%,rgba(234,234,234,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#eeeeee', endColorstr='#eaeaea',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
}

.form-control{
    height: 38px;
}

.div-logo{
    margin-top: 10px;
    margin-bottom: 20px;
}

.btn-entrar{
    color: #fff;
    height: 40px;
    font-weight: bold;
    border: 1px solid #000;
    background: #cc0000;
    background: -moz-linear-gradient(top, #cc0000 10%, #910000 100%); /* FF3.6-15 */
    background: -webkit-linear-gradient(top, #cc0000 10%,#910000 100%); /* Chrome10-25,Safari5.1-6 */
    background: linear-gradient(to bottom, #cc0000 10%,#910000 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#cc0000', endColorstr='#910000',GradientType=0 ); /* IE6-9 */
}

.btn-entrar:hover{
    color: #ffffff;
}

.direitos{
    width: auto;
    margin: 0 auto!important;
}

.direitos p{
    font-family: "Arial";
    color: black;
}

.direitos img{
    border: 1px solid #bbb;
    border-radius: 5px;
    padding: 5px;
}

.div-sidbar{
    
}

As I do not have the database to make it available, I added some images of the result obtained in my LOCALHOST, to get an idea of the application running.

Ihopethisiswhatyouwantedtodo!?Ifso,IhopeIhavehelped.

<?php//incluindoosarquivosconexãoecrudPHPrequire_once"./cls/Conexao.class.php";
     require_once "./cls/Crud.class.php";

     //verificando se existe um método GET ou POST
     if ($_POST || $_GET) {

         // Atribui uma conexão PDO   
         $pdo = Conexao::getInstance();

             //switch para verificar a opção da operação
switch ($_GET['op']) {

    //opção para listar todas as marcas da tabela MARCA
    case "marca":

        //recuperando o nome da tabela passado via AJAX e método GET
        $tabela = $_GET['tabela'];

        //instanciando a respectiva tabela
        $crud = Crud::getInstance($pdo, $_GET['tabela']);

        //instrução SQL para listar todas as marcas da tabela marca
        $sql = "SELECT * FROM $tabela";

        //não é passado nenhum parametro neste caso, já que será listado todos os registros
        $arrayParam = NULL;

        //chamando o método da classe Crud e passando os parametros
        $dados = $crud->getSQLGeneric($sql, $arrayParam, TRUE);

        //exibindo os registros da consulta para um JSON
        echo json_encode($dados);

        break;

    //opção para listar os modelos relacionados com a marca escolhida
    case "modelo":
        $tabela = $_GET['tabela'];
        $crud = Crud::getInstance($pdo, $_GET['tabela']);

        //instrução SQL para lista os modelos e como parametro o id da marca
        $sql = "SELECT * FROM $tabela WHERE id_marca = ?";

        //array de parametros, neste caso somente um o ID da MARCA
        $arrayParam = array($_GET['id_marca']);

        //chamando o método da classe Crud e passando os parametros
        $dados = $crud->getSQLGeneric($sql, $arrayParam, TRUE);

        //exibindo os registros da consulta para um JSON
        echo json_encode($dados);

        break;
}

     }

?>
    
06.05.2018 / 20:49