After selection with Select2, how to automatically fill in form fields?

Asked

Viewed 3,199 times

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 BD and return the company name to the field, example in the image below:

select2

Script in HTML:

<script language="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};
            }
          }
       });
     });

Code of the Select2 (autosuggest_busca_pessoajuridica.php) to perform the 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 BD to return the company name.

I would like that once I select the company name, all other information will be filled in automatically, based on the values contained in the BD and return in the form fields. How do I do it through Select2?

  • I don’t know what this Select2 is, a plugin or something of its own, but if I had to imagine a solution I would say that you should trigger an AJAX routine (obvious) in jQuery.click() of the elements of this field. But since I don’t know if this component adds something clickable to the element where the suggestions appear (like links, for example) I would suggest that you fire such a routine on jQuery.Blur() of the field. So you would click on the element normally, the Select2 one would fill the field with what was returned as a suggestion and when the field lost focus something else would happen.

2 answers

2


Use the method change 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 method html

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

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

});
  • Thanks for the help Gustavo. Forgive my ignorance in Ajax, but you could quote me an example, I tried this way and could not. . change(Function () { var id = $(this). val(); $.ajax({ var cnpj = $("input[name='cnpj']"); Success: Function(data){ $('#cpnj'). html(data.cpnj); } }); });

  • this ajax call would be the function of jquery: $.ajax({ url: 'url do request', data: {'Parameter 1': 'Value' }, Success: Function(){} }); for more information see this part of the API: http://api.jquery.com/jquery.ajax/

  • Thank you You, helped a lot !

0

I also found another way to solve, it is not beautiful/ elegant the code but it 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>

Browser other questions tagged

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