Concatenate variable with id fetched by Javascript

Asked

Viewed 532 times

0

Hello!

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

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

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

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

My problem is that the Javascript of the autocomplete searches for an input id called #search, but only works in the first occurrence of modal, because in the second the #search has already been used, I need then that the id of this input change following the modal, soon thought 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 have done it in small code, but I did not know how to apply in the autocomplete because I am very lay and do not understand the code well yet.

Code sample:

$(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 that calls the 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 some samples of code already with PHP 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 that calls the 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-->
  • Hello friend! It would be much better if you put the code already rendered by PHP, pure HTML so that we can analyze and even try to reproduce. Putting PHP code and database query makes the analysis 1000x more complicated because we can’t reproduce. Puts the rendered HTML and Javascript part that already helps a lot, so we can see the ids and the values already returned from PHP clearly, being able to see where the problem is and the conflicts.

  • 1

    I made an edit, I hope it helps.

  • 1

    Fernando, obg for editing the question, but I think she’s still mt big and unclear. I think in 5 lines of text you can explain what you want to do. What do you want to do? Try to synthesize what you want to do and what’s not working.

2 answers

1

When we reference an object in the document by its identifier (ID). We expect to get a single result. This is because id is just for this. 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. But in your ajax script you are capturing a single id while there are several.

Right now your idea of reasonable has turned into a major fiasco. That’s why now we’ll 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 by 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>

  • I studied earlier about identifying by class, but bumped into the same problem, as will the javascript after that, assigning a test class name for each input and changing from #test to . test there in the js file ended up working in the same way as identifying by id, the difficulty of executing in the next occurrences of the modal persisted, I’m trying to understand now your tip to try to apply here, what is not easy haha.

0

I’m sorry to have to say this but this application of yours is poorly structured and because of this, even answering the question, you will have other problems that you will not be able to solve. I often say that when the question is too complex, we’re not doing the right thing.

  1. Try to centralize and/or reuse things, for example, have only one Modal.
  2. In the modal you are using the ID SEARCH in the RG field, Ids cannot repeat, create a unique ID for each element
  3. Use the autocomplete’s callback select to call loaded Data(item.id) with the patient’s ID, from which you get all the rest
  4. On your button to open the modal use onclick="chargeHorario('09:00')" and create this function to receive the time and put the value in the modal field

I hope I’ve helped!

Good luck!

Browser other questions tagged

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