After selecting with Select2, how do I automatically fill in form fields?

1

I am creating a form that has a field that the user will enter the company name and Select2 will perform a search in the DB and return the company name to the field, example in the image below:

HTMLscript:

<scriptlanguage="JavaScript" type="text/javascript">

    $(document).ready(function() {  
      $('#nome_pj').select2({
        placeholder: "Digite o nome da empresa",
        ajax: {         
            url: 'autosuggest_busca_pessoajuridica.php',
            dataType: 'json',
            quietMillis: 50,
            data: function (term) {
                return {
                    term: term
                };
            },
            results: function (data) {
                var results = [];                   
                $.each(data, function(index, item){
                    results.push({
                        text: item.nome_pj,
                        id: item.nome_pj
                    });
                });
                return {results: results};
            }
          }
       });
     });

Select2 code ( autosuggest_busca_pessoajuridica.php ) to perform BD search:

<?php

include("lib/config.php");
include("lib/util.php");

$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("Error " . mysqli_error($con));

function destacaTexto($highlite,$string){
    return str_ireplace($highlite,"<b>".$highlite."</b>",$string);
}

//Para a busca do auto completar
$input  = (isset($_GET['term']))? htmlspecialchars($_GET['term']) :null;

$input = utf8_decode($input);

if ($input!=''){
$data = array();

function toUtf8(&$item, $key) {
    $item = iconv("iso-8859-1","utf-8",$item);
}

$query = "SELECT id_feap_pj, tipo_pj, cnpj, nome_pj, endereco_pj, num_end_pj, compl_end_pj, bairro_end_pj, cep_pj, id_mun, uf_pj, telefone_pj, email_pj, nome_representante_pj, cpf_representante_pj, data_cadastro_pj, data_alteracao_pj, id_user 
          FROM feap_pj
          WHERE nome_pj LIKE '%$input%' ";

$result = $con->query($query);  

while($row = mysqli_fetch_array($result)) {

    array_walk($row, 'toUtf8');

    extract($row);

    $json = array();
    $json['id_feap_pj'] = $id_feap_pj;
    $json['tipo_pj'] = $tipo_pj;
    $json['cnpj'] = $cnpj;
    $json['nome_pj'] = $nome_pj;
    $json['endereco_pj'] = $endereco_pj;
    $json['num_end_pj'] = $num_end_pj;
    $json['compl_end_pj'] = $compl_end_pj;
    $json['bairro_end_pj'] = $bairro_end_pj;
    $json['cep_pj'] = $cep_pj;
    $json['id_mun'] = $id_mun;
    $json['uf_pj'] = $uf_pj;
    $json['telefone_pj'] = $telefone_pj;
    $json['email_pj'] = $email_pj;
    $data[] = $json;
}

header("Content-type: application/json");
echo json_encode($data);
}

?>

Select2 works normally and can search the DB to return the company name.

I would like as soon as I select the company name, all other information is populated automatically, based on the values contained in the DB, and return in the form fields. How do I do this through Select2?

    
asked by anonymous 28.07.2014 / 16:16

2 answers

2

Use the change method and with the id that is the value selected in Select2, make an ajax call to get all the data you need and then populate the fields with the html

$('#nome_pj').select2({
            ...
}).change(function () {
     var id = $(this).val();

     $.ajax({
        ...
        success: function(data){
             $('#campo').html(data.Nome);
             ...
        }
     });

});
    
28.07.2014 / 19:07
0

I also found another way to solve it, it was not pretty / elegant, but the code works.

<script language="JavaScript" type="text/javascript">

//Preenchimento automatico depois de selecionado no autocompletar do campo nome 
$(document).ready(function() {

    //Autocompletar para seleção de nome dos clientes
    $('#nome_pj').select2({

        placeholder: "Digite o nome do produtor rural",
        ajax: {         
            url: 'autosuggest_busca_pessoajuridica.php',
            dataType: 'json',
            quietMillis: 50,
            data: function (term) {
                return {
                    term: term
                };
            },
            results: function (data) {
                var results = [];                   
                $.each(data, function(index, item){
                    results.push({
                        text: item.nome_pj,
                        id: item.nome_pj,
                        cnpj: item.cnpj,
                        endereco_pj: item.endereco_pj,
                        num_end_pj: item.num_end_pj,
                        compl_end_pj: item.compl_end_pj,
                        bairro_end_pj: item.bairro_end_pj,
                        cep_pj: item.cep_pj,
                        id_mun: item.municipio,
                        uf_pj: item.estado,
                        telefone_pj: item.telefone_pj,
                        email_pj: item.email_pj,
                        nome_representante_pj: item.nome_representante_pj,
                        cpf_representante_pj: item.cpf_representante_pj

                    });
                });                 
                return {results: results};
            }
        },
    }).on("change", preencheFormulario); 

    function preencheFormulario(el) {           
        var data = $(el.target).select2('data');
        var cnpj = data.cnpj;
        var cnpjInput = document.getElementById('cnpj');
        cnpjInput.value = cnpj;
        var endereco_pj = data.endereco_pj;         
        var enderecopjInput = document.getElementById('endereco_pj');
        enderecopjInput.value = endereco_pj;
        var num_end_pj = data.num_end_pj;
        var numendpjInput = document.getElementById('num_end_pj');
        numendpjInput.value = num_end_pj;
        var compl_end_pj = data.compl_end_pj;
        var complendpjInput = document.getElementById('compl_end_pj');
        complendpjInput.value = compl_end_pj;
        var bairro_end_pj = data.bairro_end_pj;
        var bairroendpjInput = document.getElementById('bairro_end_pj');
        bairroendpjInput.value = bairro_end_pj;
        var cep_pj = data.cep_pj;
        var ceppjInput = document.getElementById('cep_pj');
        ceppjInput.value = cep_pj;
        var id_mun = data.id_mun;
        var idmunInput = document.getElementById('id_mun');
        idmunInput.value = id_mun;
        var uf_pj = data.uf_pj;
        var ufpjInput = document.getElementById('uf_pj');
        ufpjInput.value = uf_pj; 
        var telefone_pj = data.telefone_pj;
        var telefonepjInput = document.getElementById('telefone_pj');
        telefonepjInput.value = telefone_pj;
        var email_pj = data.email_pj;
        var emailpjInput = document.getElementById('email_pj');
        emailpjInput.value = email_pj;
        var nome_representante_pj = data.nome_representante_pj;
        var nomerepresentantepjInput = document.getElementById('nome_representante_pj');
        nomerepresentantepjInput.value = nome_representante_pj;
        var cpf_representante_pj = data.cpf_representante_pj;
        var cpfrepresentantepjInput = document.getElementById('cpf_representante_pj');
        cpfrepresentantepjInput.value = cpf_representante_pj;
    }   
});

</script>
    
30.07.2014 / 16:59