How to connect two SELECT (combobox) in PHP and do AutoFill?

5

I would like to know how to connect two select . As if it had a category and a subcategory, but I want the subcategory to appear when I click on the category. I have two tables in the bd a member and another exercise, when I choose my member he list me all the exercises registered for that member.

Here, I'm showing my "category"                 

            $database = new Database();
            $db = $database->getConnection();
            $exercicio = new exercicio($db);

            $membro = new membro($db);
            $stmt = $membro->read();

        echo "<select class='form-control' name='membro_corpo'>";
            echo "<option>Select Membro...</option>";

            while ($row_category = $stmt->fetch(PDO::FETCH_ASSOC)){
                extract($row_category);
                echo "<option value='{$id_membro}'>{$nome_membro}</option>";
            }
    echo "</select>";

Now I want you to show me the "sub-categories" when I click on the category.

$stmt1 = $exercicio->read();

        echo "<select class='form-control' name='category_id'>";
            echo "<option>Select Exercicio...</option>";

            while ($row_exercicio = $stmt1->fetch(PDO::FETCH_ASSOC)){
                extract($row_exercicio);
                if($exercicio->id_membro_exer==$id_membro){
                    echo "<option value='$id_membro' selected";
                }else{
                    echo "<option value='$id_membro'";
                }
                echo "$nome_exer</option>";
            }

        echo "</select>";
    
asked by anonymous 24.09.2015 / 16:20

2 answers

3

The way I made it down is an example using ajax technology with jquery:

<div id="select_m">
 <label>Membros:</label>
  <select id="post_m" class='form-control' name='membro_corpo'>
  </select>
</div>
<div id="select_e">
  <label>Exercícios:</label>
    <select id="post_e" class='form-control' name='category_id'>
    </select>
</div>
<script src="https://code.jquery.com/jquery-latest.min.js"></script><script>$(function(){varvalor='all_members';carregarDados('ajax_select.php',valor,'m','Selecionarmembro');$('#select_e').hide();$('#select_mselect').on('change',function(){varvalor=$(this).val();hideShowInputSubmit(valor,false,'e');carregarDados('ajax_select.php',valor,'e','Selecionarexercício');});$('#select_eselect').on('change',function(){varvalor=$(this).val();hideShowInputSubmit(valor,true,'e');});});functionhideShowInputSubmit(value,submeter,elementDisplay){if(value==''){$('#select_'+elementDisplay).hide();}else{$('#select_'+elementDisplay).show();}if(submeter){//aquivocêsubmeteovalorfinalalert('Submeterformcomvalor:'+value);}}functioncarregarDados(url,valor_selecionado,id_select,default_title_value){vardata={valor_selecionado:valor_selecionado,id_formulario:id_select};$.post(url,data,function(e){varoptions=[];vardefault_option='<optionvalue="" selected>'
                            + default_title_value +
                            '</option>';

       var collection = jQuery.parseJSON(e);

       for (var i in collection) {
          options[i] = '<option value="'
                       + collection[i].id   + '">'
                       + collection[i].name + 
                       '</option>';
       }
       var opc = options.join("\n");
       var selects = [
               default_option, 
               opc
           ].join("");
       $('#post_'+id_select).html(selects);
    });    
}
</script>

In the ajax_select.php file in PHP you have to return a JSON output of $_POST['valor_selecionado'] and $_POST['id_formulario'] ( echo json_encode($seu_array) ).

Let's assume it's something like this:

<?php
if($_POST) {

    if (isset($_POST['valor_selecionado'])) {
        $id = $_POST['valor_selecionado'];

        if (in_array($id, array('1','2', 'all_members'))
            && $_POST['id_formulario'] == 'm') {
          //membros
           $return = array(
              array('id'=>'1','name'=>'Luiz'),
              array('id'=>'2','name'=>'Fábio'),
            );
        }

        if (in_array($id, array('1','2','3'))
           && $_POST['id_formulario'] == 'e') {
           //exercícios
           $return = array(
              array('id'=>'1','name'=>'Exercício 1'),
              array('id'=>'2','name'=>'Exercício 2'),
              array('id'=>'3','name'=>'Exercício 3'),
            );
        }
    }
   echo json_encode($return);  
   exit();
}


?>

If you want to test, just put the code in PHP before HTML and save a file named "ajax_select.php" and run it.

    
24.09.2015 / 17:09
1

The most practical way would be to use ajax, create a function in jquery:

(function($){
    $.subcategoria = function(id) {
        if(id != '') {
            $('select#subcategoria').html('<option value="">Carregando...</option>');
            $.post('subcategorias.php', { categoria: id }, function(data) { $('select#subcategoria').html(data); });
        } else {
            $('select#subcategoria').html('<option>Select Exercicio...</option>');
        }
    };
})(jQuery);

On your first select you add the function call:

<select class="form-control" name="membro_corpo" onchange="$.subcategoria(this.value);">

In the second select add the id subcategoria to use in the function

<select class="form-control" name="category_id" id="subcategoria">

Finally, in your php subcategoria.php (or as you wish to call) file, get the id sent via POST and list the related subcategories:

$categoria = $_POST['categoria'];
$stmt1 = $exercicio->read($categoria); // função que liste as subcategorias relacionadas
while($row_exercicio = $stmt1->fetch(PDO::FETCH_ASSOC)) {
    echo "<option value=\"$id_membro\">$nome_exer</option>";
}

You can either print to the php file the tags already ready to be included in the select field or use json and print the object and mount the tags in jquery, this is just one of several ways.

I hope it helps, hug.

    
24.09.2015 / 17:21