Concatenate variable with id searched by Javascript

0

Hello

I have a code for autocomplete here that is giving me a bit of a headache.

My code consists of a foreach that generates a line to each record found, each line generates a button that calls a modal, I put in the line that calls the modal a variable that is iterating and concatenei that variable with the id of modal, so I could connect the modal to the correct line.

<button type="button" data-toggle="modal" data-target="#modalAdicao<?php echo htmlspecialchars($idModal); ?>" class="botao btn-editar">Editar</button>

When the variable refers to the 08:00 line, the modal opens with the possibility of editing that line, until then everything is ok.

My problem is that the autocomplete Javascript looks for an input id called #busca, but only works on the first occurrence of the modal, because in the second the #busca has already been used, then I need the id of that input to change following the modal, I soon thought of the following:

<input type="text" id="busca<?php echo htmlspecialchars($idModal); ?>" placeholder="Identidade" name="rgPaciente" class="mx-sm-69 form-control" required>

The logic is simple, I've done this in small code, but I did not know how to apply in autocomplete because I'm a layman and I do not fully understand the code yet.

Sample Code:

$(function() {

    // Atribui evento e função para limpeza dos campos
    $('#busca').on('input', limpaCampos);

    // Dispara o Autocomplete a partir do segundo caracter
    $( "#busca" ).autocomplete({
        minLength: 2,
        source: function( request, response ) {
            $.ajax({
                url: "include/procura_paciente.php",
                dataType: "json",
                data: {
                    acao: 'autocomplete',
                    parametro: $('#busca').val()
                },
                success: function(data) {
                   response(data);
                }
            });
        },
        focus: function( event, ui ) {
            $("#busca").val( ui.item.rg );
            carregarDados();
            return false;
        },
        select: function( event, ui ) {
            $("#busca").val( ui.item.rg );
            return false;
        }
    })
    .autocomplete( "instance" )._renderItem = function( ul, item ) {
      return $( "<li>" )
        .append( "<br><b>Paciente: </b>" + item.nome + " - <b> RG: </b>" + item.rg + "</a><br>" )
        .appendTo( ul );
    };

    // Função para carregar os dados da consulta nos respectivos campos
    function carregarDados(){
        var busca = $('#busca').val();

        if(busca != "" && busca.length >= 2){
            $.ajax({
                url: "include/procura_paciente.php",
                dataType: "json",   
                data: {
                    acao: 'consulta',
                    parametro: $('#busca').val()
                },
                success: function( data ) {
                   $('#nomePaciente').val(data[0].nome);
                   $('#nomePaciente2').val(data[0].nome);
                   $('#rgPaciente').val(data[0].rg);
                   $('#nascimentoPaciente').val(data[0].nascimento);
                   $('#cpfPaciente').val(data[0].cpf);
                }
            });
        }
    }

    // Função para limpar os campos caso a busca esteja vazia
    function limpaCampos(){
       var busca = $('#busca').val();

       if(busca == ""){
       $('#nomePaciente').val('');
           $('#nomePaciente2').val('');
           $('#rgPaciente').val('')
           $('#nascimentoPaciente').val('')
           $('#cpfPaciente').val('')
       }
    }
});

First line calling modal:

<td>08:00 ID DA LINHA: 0</td>
<td><button type="button" data-toggle="modal" data-target="#modalAdicao0" class="botao btn-editar">Editar</button></td>

Below are some samples of PHP code already rendered: First modal:

<!-- Início do Modal de Adição de Agendamento-->
<div id="modalAdicao0" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" class="modal fade text-left">
  <div role="document" class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 id="exampleModalLabel" class="modal-title">Novo Agendamento para João Santos</h4>
        <button type="button" data-dismiss="modal" aria-label="Close" class="close"><span aria-hidden="true">×</span></button>
      </div>
      <div class="modal-body">
        <p>Preencha os campos abaixo 08:00 ID 0</p>
        <form id="novoAgendamento" method="POST" action="include/novo_agendamento.php">
          <div class="form-inline">
            <div class="form-group">
              <label for="busca" class="sr-only">Identidade</label>
              <input type="text" id="busca" placeholder="Identidade" name="rgPaciente" class="mx-sm-69 form-control procura" required>
            </div>
            <div class="form-group">
              <label for="nascimentoPaciente" class="sr-only">Nascimento</label>
              <input type="text" id="nascimentoPaciente" placeholder="Nascimento" name="nascimentoPaciente" class="mx-sm-69 form-control nascimentoPaciente" required>
            </div>
          </div>
          <div class="form-group">
            <label for="nomePaciente"></label>
            <input type="hidden" id="nomePaciente" name="nomePaciente" class="form-control nomePaciente">
            <input type="hidden" id="cpfPaciente" name="cpfPaciente" class="form-control cpfPaciente">
            <input type="hidden" id="horaPaciente" name="horaPaciente" value="08:00" class="form-control horaPaciente">
            <input type="hidden" id="dataPaciente" name="dataPaciente" value="2018-05-19" class="form-control dataPaciente">
            <input type="hidden" id="medicoPaciente" name="medicoPaciente" value="João Santos" class="form-control medicoPaciente">
            <input type="text" id="nomePaciente2" placeholder="Nome do Paciente" class="form-control nomePaciente2" disabled="">     
            <label for="observacaoPaciente"></label>
            <input type="text" name="observacaoPaciente" placeholder="Observação" class="form-control observacaoPaciente" required>
          </div>
          <div class="modal-footer">
            <button type="button" data-dismiss="modal" class="btn btn-secondary">Fechar</button>
            <button type="submit" class="btn btn-primary">Agendar</button>
          </div>
        </form>
      </div>                                      
    </div>
  </div>
</div>
<!-- Fim do Modal de Adição de Agendamento-->

Second line calling modal:

<td>09:00 ID DA LINHA: 1</td>
<td><button type="button" data-toggle="modal" data-target="#modalAdicao1" class="botao btn-editar">Editar</button></td>

Second modal:

    <!-- Início do Modal de Adição de Agendamento-->
<div id="modalAdicao1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" class="modal fade text-left">
  <div role="document" class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 id="exampleModalLabel" class="modal-title">Novo Agendamento para João Santos</h4>
        <button type="button" data-dismiss="modal" aria-label="Close" class="close"><span aria-hidden="true">×</span></button>
      </div>
      <div class="modal-body">
        <p>Preencha os campos abaixo 09:00 ID 1</p>
        <form id="novoAgendamento" method="POST" action="include/novo_agendamento.php">
          <div class="form-inline">
            <div class="form-group">
              <label for="busca" class="sr-only">Identidade</label>
              <input type="text" id="busca" placeholder="Identidade" name="rgPaciente" class="mx-sm-69 form-control procura" required>
            </div>
            <div class="form-group">
              <label for="nascimentoPaciente" class="sr-only">Nascimento</label>
              <input type="text" id="nascimentoPaciente" placeholder="Nascimento" name="nascimentoPaciente" class="mx-sm-69 form-control nascimentoPaciente" required>
            </div>
          </div>
          <div class="form-group">
            <label for="nomePaciente"></label>
            <input type="hidden" id="nomePaciente" name="nomePaciente" class="form-control nomePaciente">
            <input type="hidden" id="cpfPaciente" name="cpfPaciente" class="form-control cpfPaciente">
            <input type="hidden" id="horaPaciente" name="horaPaciente" value="09:00" class="form-control horaPaciente">
            <input type="hidden" id="dataPaciente" name="dataPaciente" value="2018-05-19" class="form-control dataPaciente">
            <input type="hidden" id="medicoPaciente" name="medicoPaciente" value="João Santos" class="form-control medicoPaciente">
            <input type="text" id="nomePaciente2" placeholder="Nome do Paciente" class="form-control nomePaciente2" disabled="">     
            <label for="observacaoPaciente"></label>
            <input type="text" name="observacaoPaciente" placeholder="Observação" class="form-control observacaoPaciente" required>
          </div>
          <div class="modal-footer">
            <button type="button" data-dismiss="modal" class="btn btn-secondary">Fechar</button>
            <button type="submit" class="btn btn-primary">Agendar</button>
          </div>
        </form>
      </div>                                      
    </div>
  </div>
</div>
<!-- Fim do Modal de Adição de Agendamento-->
    
asked by anonymous 19.05.2018 / 04:57

2 answers

0

I'm sorry to have to say this but your application is poorly structured and due to this, even answering the question, you will have other problems that you will not have to solve. I often say that when the question is too complex, we are not doing the right thing.

  • Try to centralize and / or reuse things, such as having only one Modal.
  • In the modal you are using the ID SEARCH in the RG field, IDs can not be repeated, create a unique ID for each element
  • Use the autocomplete select callback to call loadsData (item.id) with p Patient ID, from it you get all the rest
  • On your open modal button use onclick="loadHorario ('09: 00 ')" and create this function to receive the time and put the value in the field in modal
  • I hope I have helped!

    Good luck!

        
    19.05.2018 / 05:40
    0

    When we refer to an object in the document by its identifier (ID). We expect to get a single result. That's because the id is right for that. To be unique. Your idea:

    <input type="text" id="busca<?php echo htmlspecialchars($idModal); ?>" placeholder="Identidade" name="rgPaciente" class="mx-sm-69 form-control" required>
    

    It seems to be reasonable because it links the search to a specific id. However in your ajax script you are capturing a single id while there are several.

    Right now your idea of reasonable has become a big fiasco. That's because now we're going to have to worry about relating these ids to the selector in the ajax function. A simpler solution is to select the values through the use of classes passing the id of the search field to be used in the return of the data. This is ! To know where to put the search result. Ex. $('#nome-'+id) :

     $( document ).ready(function() {
            $('.busca').change(function(){
                busca(this.value , this.id);
            })
    
            function busca(busca , id){
                // Busca
                let resultado =  'resultato para a busca ' + busca;
                //Retornando os resultados
                $('#nome-'+id).val(resultado);
            }
            
     });   
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <form action="">
            <input id="1" class="busca" type="text">Busca
        <input id="nome-1" type="text">Resultado
        </form>
        <form action="">
            <input id="2" class="busca" type="text">Busca
            <input id="nome-2" type="text">Resultado
        </form>
        <form action="">
            <input id="3" class="busca" type="text">Busca
            <input id="nome-3" type="text">Resultado
        </form>
    </body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.js"></script>
    </html>
        
    19.05.2018 / 05:53