Combobox receive data in the second field (list menu)

Asked

Viewed 961 times

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. For example, make of cars and models. In the first select the brands and in the second select the models.

Testing: I’ve tried several video formats on Youtube and from here, I searched on Google and some work but most do not work and even when I adapt to the problem I need to solve ends up not working.

What I have: Mysql with all information. Two tables, one table only with tags and the other table with 2 columns (tag and template).

Last test: I tried to do a While to search, while the "value" of a select is the same as the other table, display the model records of the second table, only it only returns blank value. The connection of the database is working, because I do the test and returns result (by Dreamweaver) but the menu list box shows no result. Javascript command 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>
  • I didn’t really understand your question. Is there any way to edit the question and start text by itself and not explain the last attempts? Type being more specific even.

  • Edited, separated by sector, ta good now?

1 answer

0

This is César Mattos!

From what I understand, you want to make the famous "Combobox in Cascade", that is, the completion of one depends 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 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 don’t have the database to provide, I added some images of the result obtained in my LOCALHOST, to get an idea of the application running.

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

I hope that’s what you’ve been wanting to do!? If so, I hope I’ve helped.

Follows code from the PHP file that would be the AJAX URL

<?php

     //incluindo os arquivos conexão e crud PHP
     require_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;
}

     }

?>
  • (I’m doing a test run now but I’ve come up with a question) Usually in value and text combination schedules they use comparison ID with a number, I always try to make that comparison with string, type, instead of comparing 1 == 1, I try to compare "Ford" == "Ford", it can give me trouble or indifference?

  • That line url: 'processa-ajax.php?op=' + 'marca' + '&tabela=' + 'tbl_marca' , how do I connect to BD? (tbm to using localhost) I searched "url connection ajax sql" and returned things nothing to see, I must be looking for the wrong information.

  • Ahh I’m sorry, I just forgot to put the PHP script...

  • Regarding your question of comparison, it is indifferent the type of comparison you will make (integer, string), depends on your logic and your programming. What you should note is that the languages have their respective commands to compare Strings. Ex: PHP (https://www.w3schools.com/php/func_string_strcmp.asp), JAVASCRIPT (https://www.w3schools.com/jsref/jsref_localecompare.asp). Nothing prevents you from using operator '==', however, you should do some tests to see if the comparison is working properly. I have had problems with this in JAVA, in other languages until today not.

  • I spent all the same, I changed the fields in PHP in the GET switch pro BD name, the 2 GET brand and model by table name but it didn’t work, I believe the require_once "./cls/Crud.class.php"; that I don’t have.

  • I made the complete project available in the link below. It also contains sql database, only import to your Mysql. Don’t forget to check in the file "Conexao.php" the constants for the connection to the database according to your settings. Link: https://www.dropbox.com/s/1wkecr8n6p09vro/selects_cascata.rar?dl=0

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.