Pass the value of 2 <select> using jQuery

Asked

Viewed 187 times

-1

I have a option select that when selecting an option it goes in BD and returns the value to another option select, works perfectly.

index with the option select:

<?php
require './conexao.php';
?>
<!DOCTYPE html>
    <html>
        <head>
            <title>Atualizando combos com jquery</title>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <script type="text/javascript">
            $(document).ready(function () {
                $('#funcao').change(function () {
                    $('#tipo').load('listaFuncoes.php?funcao=' + $('#funcao').val());
                }).change();
            });
        </script>
        </head>
        <body>
            <h1>Atualizando combos com jquery</h1>
            <label>Função:</label>
            <select name="funcao" id="funcao">
                <option value="">selecione</option>
                <?php
                $rs = mysqli_query($conexao, "SELECT * FROM funcao ORDER BY nome");
                for ($i = 0; $i < mysqli_num_rows($rs); $i++) {
                    $linha_funcao = mysqli_fetch_array($rs);
                    ?>
                    <option value="<?= $linha_funcao[0] ?>"><?php echo $linha_funcao[1] ?></option>
                    <?php
                }
                ?>
            </select>
            <br /><br />
            <div id="tipo">
            </div>
        </body>
    </html>

and my listaFuncoes.php where it is fed with the result of the 1st option:

<?php
require './conexao.php';

$id_estado = $_GET['funcao'];

$select_func = "SELECT DISTINCT tp.idfuncao, tpd.id ,tpd.descricao "
        . "FROM tipos_prova tp "
        . "INNER JOIN tipos_prova_descricao tpd ON tpd.idDescricao = tp.desctipoprova "
        . "WHERE tp.idfuncao = '$id_estado' "
        . "ORDER BY tpd.descricao";
$rs = mysqli_query($conexao, $select_func); 

echo "<select class='custom-select mb-3' name='tipo' required>
        <option value=''>selecione</option>";
for ($i = 0; $i < mysqli_num_rows($rs); $i++) {
    $linha_funcao = mysqli_fetch_array($rs);
    ?>
    <option value="<?= $linha_funcao[0] ?>"><?php echo $linha_funcao[2] ?></option>
    <?php
}
echo "</select>";

Here comes the problem, now I need a third option select and receives the values passed from the 1st and 2nd option select after choosing the option of the 2nd option, how to solve?

Ex: 1st option passes value=1. 2nd option passes value=3. and in the third option I need these 2 values.

2 answers

0


The best option to solve your problem is using Javascript.

Add an ID to each of your select, example:

<select id="list1">
  <option value=""></option>
</select>

<select id="list2">
  <option value=""></option>
</select>

<select id="list3">
  <option value=""></option>
</select>

Now to get the values of each select, it’s quite simple, you can use jQuery, add the scripts to the end of your code.

Example:

<script
  src="https://code.jquery.com/jquery-3.4.1.js"
  integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
  crossorigin="anonymous"></script>

<script>
  $(document).ready(function(){
    $('#list1').change(function(){
      alert(this.value); // valor que o usuário escolheu para a lista 1
    });

    $('#list2').change(function(){
      alert(this.value); // valor que o usuário escolheu para a lista 2
    });

    $('#list3').change(function(){
      alert(this.value); // valor que o usuário escolheu para a lista 3
    });
  });
</script>

Just be careful not to import the jQuery library more than once, if you already have jQuery don’t need to import again.

  • It would not solve, because I need you to send the value of the 1st select next to the 2nd select, type Country/State/City search. he will take the city of the state of that particular country.

  • You can assign to a variable outside the scope the values, it can be even an object, something like 'const Location = { select1: 'Valor3', Select2: 'valor2', select3: 'Valor3' }', and your this.value of each chage will set in the value of the corresponding property of the object.

0

Create callback files for each query in the database and make the calls via ajax, which will generate a chain reaction and change all subsequent selects.

This also makes it much easier to maintain your code.

I will use the example of Country/State/City and follow this hierarchy.

Inside the index, leave the selects empty, but with name and id defined. Who will popular these selects is the js with the information that php will return to it via json.

index php.

<body>

<select name="pais" id="pais"></select>
<select name="estado" id="estado"></select>
<select name="cidade" id="cidade"></select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="popularSelects.js"></script>
<script src="retornarPais.php?callback=retornarPais"></script>

Now just write the search files. retPais.php - This is preloaded in index and returns all countries in table

require_once "conexao.php";

$callback = isset($_GET['callback']) ?  $_GET['callback'] : false;
$query = "SELECT paisId, pais FROM pais";
$paises = mysqli_query($conecta,$query);
$retorno = array();
while($linha = mysqli_fetch_object($paises))
{
    $retorno[] = $linha;
}   
echo ($callback ? $callback . '(' : '') . json_encode($retorno) . ($callback? ')' : '');

mysqli_close($conecta);

returnState.php - Called whenever there is a change in the country.

require_once "conexao.php";

$callback = isset($_GET['callback']) ?  $_GET['callback'] : false;
if(isset($_GET['paisId'])) 
{
    $paisID = $_GET['paisId'];
}
else
{
    $paisID = 1;
}
$query  = "SELECT estadoId, estado FROM estados ";
$query .= "WHERE paisId = {$paisID}";
$estados = mysqli_query($conecta,$query);
$retorno = array();
while($linha = mysqli_fetch_object($estados))
{
    $retorno[] = $linha;
}   
echo json_encode($retorno);

mysqli_close($conecta);

returnCity.php - Whenever you change the state

require_once "conexao.php";

$callback = isset($_GET['callback']) ?  $_GET['callback'] : false;
if(isset($_GET['paisId']) && isset($_GET['estadoId'])) 
{
    $paisID = $_GET['paisId'];
    $estadoID = $_GET['estadoId'];
}
else
{
    $paisID = 1;
    $estadoID = 1;
}
$query  = "SELECT cidadeId, cidade FROM cidades ";
$query .= "WHERE paisId = {$paisID} AND estadoId = {$estadoID}";
$cidades = mysqli_query($conecta,$query);
$retorno = array();
while($linha = mysqli_fetch_object($cidades))
{
    $retorno[] = $linha;
}   
echo json_encode($retorno);

mysqli_close($conecta);

popularSelects.js

function retornarPais(data)           
{
    var pais = "";
    $pais_id = $("#pais").val();
    $.each(data, function(chave, valor){
        if ($pais_id == valor.paisId)
        {
            pais += '<option value="' + valor.paisId + '" selected>' + valor.pais + '</option>';
        }
        else
        {
            pais += '<option value="' + valor.paisId + '">' + valor.pais + '</option>';
        }
    });
    $("#pais").html(pais);
}
function carregarEstados()                  
{
    var pais_id = $('#pais').val();

    $.ajax ({
        type:"GET",
        data:"paisId=" + pais_id,
        url:"retornarEstados.php",
        async: false

    }).done(function(data){
        var estado = "";
        $estado_id = $("#estado").val();
        $.each($.parseJSON(data), function(chave, valor){
            if ($estado_id == valor.estadoId)
            {
                estado += '<option value="' + valor.estadoId + '" selected>' + valor.estado + '</option>';
            }
            else
            {
                estado += '<option value="' + valor.estadoId + '">' + valor.estado + '</option>';
            }
        });
        $("#estado").html(estado);
    });
}

function carregarCidades()                  
{
    var pais_id = $('#pais').val();
    var estado_id = $('#estado').val();

    $.ajax ({
        type:"GET",
        data:"paisId=" + pais_id + "&estadoId=" + estado_id,
        url:"retornarCidades.php",
        async: false

    }).done(function(data){
        var cidade = "";
        $cidade_id = $("#estado").val();
        $.each($.parseJSON(data), function(chave, valor){
            if ($cidade_id == valor.cidadeId)
            {
                cidade += '<option value="' + valor.cidadeId + '" selected>' + valor.cidade + '</option>';
            }
            else
            {
                cidade += '<option value="' + valor.cidadeId + '">' + valor.cidade + '</option>';
            }
        });
        $("#cidade").html(cidade);
    });
}

$(document).ready(function()
{
    carregarEstados();
    carregarCidades();
});
$("#pais").change(function()
{
    carregarEstados();
    carregarCidades();
});

$("#estado").change(function()
{
    carregarCidades();
});

I used very simple examples to make it easier to read the code. But inside the return files you can increase the complexity of querys without problems.

Browser other questions tagged

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