Fill inputs after insertion via Jquery

Asked

Viewed 60 times

-1

I have a problem I don’t know how to fix. I have an Ajax function q makes a query based on the chosen item of a select. After the query and received the search data on the front end, I fill in the inputs with the data, such as: Name of the Agreement, Street, Neighborhood, etc... But there are phones, which can be more than one depending on the agreement. I created a function that fills a div with the phone fields, which is working, but I’m not able to enter the phone values inside these inputs. I tried to create an array outside of the Ajax function and do something after that, but it also didn’t work. I need some idea of how this can be done.

<form action="/dashboard/convenio/update" method="POST">
                    @csrf                    
                    <meta name="csrf-token" content="{{ csrf_token() }}">
                    <div class="row">
                        <div class="input-fiel col s12">
                            <select name="cod_convenio" id="cod_convneio" class="select">
                                <option value="" disabled selected>Escolha o Convênio</option>
                                @foreach($results as $result)
                                    <option value="{{ $result->cod_convenio }}">{{ $result->nome_convenio }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="input-field col s12">
                            <input id="nome_edit" name="nome_convenio" type="text" class="validate">
                            <label for="nome_convenio">Nome do Convênio</label>
                        </div>
                    </div>
                    <div class="row">
                        <div class="input-field col s4">
                            <input placeholder="Rua, Avenida..." id="rua_edit" name="rua_convenio" type="text" class="validate">
                            <label for="rua_edit">Rua</label>
                        </div>
                        <div class="input-field col s4">
                            <input id="bairro_edit" palceholder="Bairro" name="bairro_convenio" type="text" class="validate">
                            <label for="bairro_edit">Bairro</label>
                        </div>
                        <div class="input-field col s4">
                            <input id="cidade_edit" placeholder="Cidade" name="cidade_convenio" type="text" class="validate">
                            <label for="cidade">Cidade</label>
                        </div>
                    </div>
                    <div class="row">
                        <div id="reference_edit">
                            <div class="input-field col s2">
                                <i class="material-icons prefix">phone</i>
                                <input id="input-field col s3 icon_telephone" name="telefone[]" type="tel" class="validate">
                                <a id="add" class="btn-floating btn-small waves-effect waves-light green">
                                    <i class="material-icons">add</i>
                                </a>
                                <label for="icon_telephone">Telefone</label>
                            </div>
                        </div>                            
                        <div id="insert_edit"></div> 
                        <script src="{{ asset('js/searchConvenio.js') }}"></script>
                    </div> 
                    <div class="divider"></div>
                        <p>
                            <label>
                                <input type="checkbox"/>
                                <span>Ativado</span>
                            </label>
                        </p>
                    <button class="btn waves-effect waves-light" type="submit" name="action">Alterar
                        <i class="material-icons right">send</i>
                    </button>
                </form>
let telefones = new Array()

$(document).ready(function(){

    $('#cod_convneio').change(function(){

        // console.log('im working!')   

        let cod = $(this).val()

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            url: '/dashboard/convenio/find',
            type: 'POST',
            data: {cod},
            success: function(result){

                $('#insert_edit').empty()
                telefones = []

                $('#nome_edit').val(result['nome_convenio'])
                $('#rua_edit').val(result['rua_convenio'])
                $('#bairro_edit').val(result['bairro_convenio'])
                $('#cidade_edit').val(result['cidade_convenio'])

                for(var i=0;i<result['telefones'].length;i++){

                    const htmlString = '<div id="telefone'+i+'" class="input-field col s2"><input maxlength="14" id="input-field col s3 icon_telephone edit'+i+'" name="telefone[]" type="tel" class="validate"><a id="remove" class="btn-floating btn-small waves-effect waves-light red"><i class="material-icons">remove</i></a><label for="icon_telephone">Telefone</label></div>'

                    $(htmlString).appendTo('#insert_edit')

                    telefones[i] = result['telefones'][i]['numero_telefone']                   

                }
            }
        }) 
        
        $(document).change(function(){    

            console.log(telefones)
        
            for(var i=0;i<telefones.length;i++){ 
                //console.log(telefones[i]) 
                $('#input-field col s3 icon_telephone edit'+i).val(telefones[i]['numero_telefone'])
            }
        
        })
    })
})

  • Hi friend, how is the return Json structure of the url "Dashboard/Convenio/find"?

  • Is that way {nome_convenio: "Unimed", rua_convenio: "Av Barao do Rio Branco", bairro_convenio: "Centro", cidade_convenio: "Juiz de Fora", telefones: Array(2), …}&#xA;activated: 1&#xA;bairro_convenio: "Centro"&#xA;cidade_convenio: "Juiz de Fora"&#xA;nome_convenio: "Unimed"&#xA;rua_convenio: "Av Barao do Rio Branco"&#xA;telefones: Array(2)&#xA;0:&#xA;numero_telefone: "32 3232-1122"&#xA;__proto__: Object&#xA;1:&#xA;numero_telefone: "32 3525-9100"&#xA;__proto__: Object

  • Thanks, one more question, what appears if you log console inside the is, in result['phones']

1 answer

0


You can build dynamically on the return of the request the inputs via jquery example:

........
         success: function(result){
                $('#insert_edit').empty()
                $('#nome_edit').val(result['nome_convenio'])
                $('#rua_edit').val(result['rua_convenio'])
                $('#bairro_edit').val(result['bairro_convenio'])
                $('#cidade_edit').val(result['cidade_convenio'])      
                
                if(result['telefones'] && result['telefones'].length) {
                  $.each(result['telefones'], function(i, telefone) {
                   $('#insert_edit').append(      
                     $('<div>', {'id':'telefone'+i, 'class':'input-field col s2'}).append(
                       $('<input>', {'id': 'input-field col s3 icon_telephone edit'+i, 'name': 'telefone[]', 'type': 'tel', 'class': 'validate', 'maxlength': '14', 'text': telefone}),
                       $('<a>', {'id':'remove', 'class':'btn-floating btn-small waves-effect waves-light red'}).append(
                         $('<i>', {'class': 'material-icons', 'text': 'Remove'})
                       )
                   ),
                   $('<label>', {'for': 'icon_telephone', 'text': 'Telefone'})
                  )    
                 });
                }
         }

You were creating a global variable to access later to display on screen, this is not a good practice.

Another issue the ids of the selectors are very large, may be more precise, if you are going to use something for style I suggest using only classes, keeping the ids only for events and assignments.

  • Thank you so much!! I knew there was something I was doing wrong, I just couldn’t see.

Browser other questions tagged

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