Displays items as selected from a select (HTML)

Asked

Viewed 1,716 times

3

Good afternoon!

I have a database with two tables, products and menus, the two tables are indexed through the Cdcardapio field. I created an html select element that contains all the registered menus, I need that when selected, for example, the menu "Drinks", only the products that Cdcardapio is equal to the selected are listed. However, I need this to happen without updating the page, here’s the problem, I haven’t learned to work very well with jQuery and Ajax, someone can help me?

I already have the code that lists the existing menus:

            <select class="form-control" id="cardapio" name="CdCardapio">
            <option value=""> Selecione um Cardápio </option>       
            <?php foreach($cardapios as $cardapio) : ?>
                <option class="cardapio" value="<?=$cardapio['CdCardapio']?>">
                               <?=$cardapio['nomeCardapio']?>
                </option>
            <?php endforeach ?>
            </select>   

Now I need that according to the selected menu, the products belonging to it are listed in the table below, which, now, I am listing all products, see:

        <table class="table table-bordered">
         <tr class="active">
             <td>
                 <b>Produto</b>
             </td>
             <td>
                 <b>Valor</b>
             </td>
             <td>
                 <b>Quantidade</b>  
             </td>
         </tr>
         <?php
           $produtos = listaProdutos($conexao);
           foreach($produtos as $produto) :
         ?>

        <tr class="produto">
            <td hidden><?=$produto['CdProduto'] ?></td> 
            <td hidden><?=$produto['CdCardapio'] ?></td>        
            <td><?=$produto['nomeProduto'] ?></td>
            <td><div class="valor"><?=$produto['valorProduto']?></div></td>
            <td>
                <input class="quantidade" type="number" value="0" size="1" maxlength="2" max="10" min="0" step="0">
            </td>
        </tr>

        <?php
             endforeach;
        ?>
    </table>

Function listProducts:

function listaProdutos($conexao) {
     $produtos = array ();
     $resultado = mysqli_query($conexao, "select p.*, c.nomeCardapio 
                                          from cardapios c, produtos p
                                          where c.CdCardapio = p.CdCardapio");
     while($produto = mysqli_fetch_assoc($resultado)) {
                  array_push($produtos, $produto);
                  }
                  return $produtos;
     }

I think it’s clear now, sorry for the inconvenience!!

  • 2

    Have you tried anything? If so, post your code with the specific problem. If we wouldn’t have to create the whole routine from scratch.

  • The posted solution gives you to adapt, Status => Menu / City => Products...

  • But why don’t you adjust it like I showed you?

  • 1

    When you posted I was editing my question! I will adjust it as soon as it is ready I put it here. Thanks André!

  • Okay, anything if you can’t, post what you can adjust and we’ll analyze it here and help you finish. Thanks! ;)

  • Okay, I have a question, in my case I need to show the data in a table, not in a select, to be specific are two database fields that I need to load in this table. To click on select, I did some examples here and it worked, but I don’t know how I could do it.

  • You can do it too, you got it right?

Show 2 more comments

2 answers

6


Hello @Fred could try otherwise using only HTML and JS

That way (I don’t know if it would solve your problem):

var arr_cidades = {
  sp: ["Sorocaba", "Boituva", "Tatuí"],
  rj: ["Uma cidade do Rio", "Outra cidade"]
}

function escolha() {
  var estado = document.querySelector("#estado");
  var cidade = document.querySelector("#cidade");

  cidade.disabled = false;

  cidade.innerHTML = "";

  switch (estado.value) {
    case "sp":
      for (i in arr_cidades.sp) {
        cidade.innerHTML += "<option>" + arr_cidades.sp[i] + "</option>"
      };
      break;
    case "rj":
      for (i in arr_cidades.rj) {
        cidade.innerHTML += "<option>" + arr_cidades.rj[i] + "</option>"
      };
      break;
    default:
      cidade.innerHTML += "<option>- Selecione uma cidade -</option>";
      cidade.disabled = true;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Estado</span>
<br>
<select id='estado' onchange="escolha()">
  <option value=''>- Selecione um Estado -</option>
  <option value='sp'>SP</option>
  <option value='rj'>RJ</option>
</select>
<br>
<br>
<span>Cidade</span>
<br>
<select id='cidade' disabled="true">
  <option value=''>- Selecione uma Cidade -</option>
    </select>

In the case of Var Arr_cities you can enter the options you want for each product category variation!

  • Almost that right... Only he would have to search the database!

2

The Menu file you can do this way:

<form method="post" enctype="multipart/form-data">
    <select onchange="getBebidas()" name="idCardapio" id="idCardapio">
        <option value="0">Selecione o Cardápio</option>
        <!---- Aqui você monta a listagem de todos os ítens do cardápio... todos os tipos. --->
        <option value="1">Cardapio 1</option>
        <option value="2">Cardapio 2</option>
    </select>

    <select name="listaBebidas" id="listaBebidas" class="listaBebidas">
        <option value="0">Primeiro Selecione o Cardápio</option>
    </select>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
    function getBebidas() {
        var id = $('#idCardapio').val();
        $(".listaBebidas").append('<option value="0">Carregando...</option>');
        $.post("cardapio_sql.php?idCardapio=" + id,
            {listaBebidas:jQuery(id).val()},
            function(valor){
                 $(".listaBebidas").html(valor);
            }
        );
    }
</script>

cardapio_sql.php

<!--- Neste arquivo, você faz a conexão com o banco de dados, use o POST['idCardapio'] para pegar o ID do cardápio e faz um SQL com os dados e o while exibindo os resultados apenas em <option> sem precisar do <select> -->
<option>teste</option>
<option>teste2</option>

Good luck!

Browser other questions tagged

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