Complete fields from a field with mask

Asked

Viewed 260 times

1

I have a function that completes the fields tipo logradouro, endereço, bairro, cidade e estado from the moment the user informs the cep. But I have a mask in the zip code field, and since the records in the database are without characters, it does not return the data.

I have 2 questions

1st: there is a possibility that I can fill in the fields from the ZIP code with mask?

2nd: There is possibility of I bring the fields from the database and as they are returned get the mask to be displayed with characters?

index php.

    <script type='text/javascript'>
        $(document).ready(function(){
                $("input[name='cep']").blur(function(){
                        var $tipo_logr = $("input[name='tipo_logr']");
                        var $nome_logr = $("input[name='nome_logr']");
                        var $bairro = $("input[name='bairro']");
                        var $cidade = $("input[name='cidade']");
                        var $estado = $("input[name='estado']");
                        
                        $.getJSON('function_func.php',{ 
                                cep: $( this ).val() 
                        },function( json ){
                                $tipo_logr.val ( json.tipo_logr );
                                $nome_logr.val ( json.nome_logr );
                                $bairro.val ( json.bairro );
                                $cidade.val ( json.cidade );
                                $estado.val ( json.estado );
                        });
                });
        });    
    </script>

    <script type="text/javascript">
        $(document).ready(function(){
            $('#cep').mask('00000-000');
            $('#fone').mask('0000-0000');
            $('#fax').mask('0000-0000');
            $('#data_nascimento').mask('00/00/0000');
        });
    </script>

    <div class="col-lg-12">
        <div class="col-lg-4"><!-- Inicio Input CEP -->
            <label for="ex1">Cep: </label>
            <input type="text" class="form-control" id='cep' name='cep' maxlength='8' placeholder='_____-___'><br>
        </div><!-- Fim Input CEP -->

        <div class="col-lg-8"><!-- Inicio Input Tipo Logradouro -->
            <label for="ex1">Tipo Logradouro: </label>
            <input class="form-control" type="text" name="tipo_logr" maxlength='4'><br>
        </div><!-- Fim Input Tipo Logradouro -->
    </div>

    <div class="col-lg-12">
        <div class="col-lg-12"><!-- Inicio Input Endereco -->
            <label for="ex1">Endereço: </label>
            <input type="text" class="form-control" name="nome_logr" maxlength='40'><br>
        </div><!-- Fim Input Endereco -->
    </div>

    <div class="col-lg-12">
        <div class="col-lg-12"><!-- Inicio Input Bairro -->
            <label for="ex1">Bairro: </label>
            <input type="text" class="form-control" name="bairro" maxlength='30'><br>
        </div><!-- Fim Input Bairro -->
    </div>

    <div class="col-lg-12">
        <div class="col-lg-8"><!-- Inicio Input Cidade-->
            <label for="ex1">Cidade: </label>
            <input type="text" class="form-control" name="cidade" maxlength='30'><br>
        </div><!-- Fim Input Cidade -->

        <div class="col-lg-4"><!-- Inicio Input Estado -->
            <label for="ex1">Estado: </label>
            <input name="estado" type="text" class="form-control" name="estado" maxlength='2'><br>
        </div><!-- Fim Input Estado -->                                
    </div>

function_func.php

<?php     

include_once("conn.php");

function ret($cep, $conn){

    $result = "SELECT * FROM cadcep WHERE cep = '$cep' LIMIT 1";

    $resultado = $conn->query($result);

    // DECLARA A VARIAVEL
    $valores = array();

    if($resultado){

        $row = mysqli_fetch_assoc($resultado);
        $valores['tipo_logr'] = $row['tipo_logr'];
        $valores['nome_logr'] = $row['nome_logr'];
        $valores['bairro'] = $row['bairro'];
        $valores['cidade'] = $row['cidade'];
        $valores['estado'] = $row['estado'];


    } else {
        return json_encode(array( 'error' => mysqli_error($conn) ));        
    }

        return json_encode($valores);

}

if(isset($_GET['cep'])){
        echo ret($_GET['cep'], $conn);
}
?>
  • Do you want to take the value typed by the user with mask and remove it when searching in the correct bank? which fields you should be masked in return?

  • that’s right, the fields I wanted you to come back with a mask are: phone and fax, but I want to learn this to use this if you need it in the future

  • But php does not return these fields (phone, fax etc)

  • is returning normally but the user informs 3333-3333 at the time of entering the record in the database, and I delete the characters to save and is inserted so 33333333 without the '-' wanted to know if I have how to bring it with - to display to the user, only a doubt whether it is possible or not, and the other is whether I can remove the mask from the cep field when searching for the record in the database

1 answer

1


1 - To keep the mask in the field and search, remove the special characters inside the function:

function ret($cep, $conn){

    $a_cep = str_replace(".", "", $cep);
    $b_cep = str_replace("-", "", $a_cep);
    $result = "SELECT * FROM cadcep WHERE cep = '$b_cep' LIMIT 1";

2 - To set the mask, order it to run again after the values have been filled in, and replace the '0' (indica apenas o padrão da máscara) por'9'(indicates what the default is numerical)`:

$.getJSON('function_func.php',{ 
    cep: $( this ).val() 
},function( json ){
    $tipo_logr.val ( json.tipo_logr );
    $nome_logr.val ( json.nome_logr );
    $bairro.val ( json.bairro );
    $cidade.val ( json.cidade );
    $estado.val ( json.estado );

    $('#cep').mask('99999-999');
    $('#fone').mask('9999-9999');
    $('#fax').mask('9999-9999');
    $('#data_nascimento').mask('99/99/9999');
});

NOTE: Personally I find the plugin https://github.com/RobinHerbots/Inputmask better to create masks, it keeps formatting independent of the time of filling.

  • Thanks, I’ve never seen this plugin, I’ll study about it. The answer 1- worked, but the 2 keeps returning with the data without characters, I had already tried this way and was unsuccessful

  • @Victort. tries to replace '0' with '9'

  • 1

    now was, our did not know of this distinction, thank you so much for sharing your wisdom

  • I recommend reading the documentation , these are simple details that sometimes we don’t even notice kk, I updated the answer with the correct one, from a read there, the '0' is to indicate any pattern, the '9' serves to indicate that it is numerical, and there are some others, but that’s not the case.

  • If you are going to use this plugin you can use $('#cep').inputmask('unmaskedvalue'); to take the value without mask, in some situations it is useful :)

Browser other questions tagged

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