Ajax to make select in bank does not work on new line

0

I am having difficulty in the following situation, when generating a new row of the table my Ajax code to make a select in the bank does not work. Follow the image below to clarify any doubts:

Page:

<divclass="form-group">
   <label class="control-label col-lg-4">Víncular Bolsistas:</label>
   <div class="control-label col-lg-9 col-lg-offset-1">
      <div class="form-horizontal">
         <div class="table-responsive">
            <table class="table table-bordered table-striped table-highlight">
               <thead>
                  <div class="row">
                     <th class="col-xs-5 col-sm-5 col-md-5 col-lg-5">Nome</th>
                     <th class="col-xs-4 col-sm-4 col-md-4 col-lg-4  ">Vinculo</th>
                     <th class="col-xs-2 col-sm-2 col-md-2 col-lg-2">Horas</th>
                     <th class="col-xs-1 col-sm-1 col-md-1 col-lg-1"></th>
                  </div>
               </thead>
               <tbody id="tabelaCorpo">
                  <tr id="linhaParaClonar">
                     <td>
                        <select class="bolsista form-control" name="bolsista[0]"></select>
                     </td>
                     <td>
                        <label class="radio-inline">
                        <input type="radio" name="vinculo[0]" value="1">Bolsista</label>
                        <label class="radio-inline">
                        <input type="radio" name="vinculo[0]" value="2">Voluntário</label>
                     </td>
                     <td>
                        <div class=" col-lg-12">
                           <select class="form-control" name="horas[0]">
                              <option value="02:00:00">2</option> 
                              <option value="06:00:00">4</option>
                              <option value="08:00:00">8</option>
                              <option value="16:00:00">16</option>
                           </select>
                        </div>
                        <!-- <input type="number" name="horas[0]" class="form-control" /> -->
                     </td>
                     <td>
                        <!-- <button onclick="removerLinha()" class="glyphicon glyphicon-remove"></button> -->
                     </td>
                  </tr>
               </tbody>
            </table>
            <div class="col-sm-offset-8">
               <input type="button" onclick="clonarLinha()" value="Adicionar" id="adcLinha" class="btn btn-success">
            </div>
         </div>
      </div>
   </div> 
</div>
</div>
</div>
<!--     </div> -->
<div class="row" id="box-cinza-inferior">
   <div class="col-lg-offset-1 col-sm-2">
      <a href="menu-extensao.php" class="btn btn-success" onClick="formVazio();">Voltar</a>
   </div>
   <div class="col-lg-offset-10" >
      <button type="submit" class="btn btn-success">Concluir</button>
   </div>
</div>
</form>
</div>

JavaScript code to add line:

function clonarLinha() {
   if (x <= campos_max) {
       $('#tabelaCorpo').append('<tr id="linhaClonada">\
         <td id="atualizarBolsista">\
              <select class="bolsista form-control" name="bolsista[' + x + ']"></select>\
         </td>\
          <td><label class="radio-inline">\
          <input type="radio" name="vinculo[' + x + ']" value="1">Bolsista</label>\
          <label class="radio-inline">\
          <input type="radio" name="vinculo[' + x + ']" value="2">Voluntário</label>\
         </td>\
         <td>\
             <div class=" col-lg-12">\
                 <select class="form-control" name="horas[0]">\
                     <option value="02:00:00">2</option> \
                     <option value="06:00:00">4</option>\
                     <option value="08:00:00">8</option>\
                     <option value="16:00:00">16</option>\
                 </select>\
             </div>\
         </td>\
         <td>\
             <input type="button" onclick="removerLinha(this)" class="btnX btn btn-danger" value="X">\
         </td>\
         </tr>');
       x++;
   }
}

Ajax:

// Campo autocomplete que busca no banco o nome do aluno
$('.bolsista').select2({
   placeholder: 'Selecione um aluno',
   ajax: {
      url: '../php/ajaxSelectAluno.php',
      dataType: 'json',
      delay: 250,
      processResults: function (data) {
         return {
            results: data
         };
      },
      cache: true
   }
});

AjaxSelectAluno:

<?php
include ("../classe/conexao.php");
$sql = "SELECT p.id as id, p.nome
FROM pessoa p
JOIN aluno a ON a.aluno_id_pessoa = p.id
WHERE nome LIKE '%".$_GET['q']."%'
LIMIT 10"; 

# WHERE nome LIKE '%".$_GET['q']."%'
$result = $mysqli->query($sql);

$json = [];

while($row = $result->fetch_assoc()){
   $json[] = ['id'=>$row['id'], 'text'=>$row['nome']];
}

echo json_encode($json);
    
asked by anonymous 26.11.2017 / 17:28

1 answer

0

I suggest creating a function of your own to apply select2 :

function aplicaSelect2(){
   $('.bolsista').select2({
      placeholder: 'Selecione um aluno',
      ajax: {
         url: '../php/ajaxSelectAluno.php',
         dataType: 'json',
         delay: 250,
         processResults: function (data) {
            return {
               results: data
            };
         },
         cache: true
      }
   });
}

In this way, every time a row is added, select2 will be applied to the added rows.

Also add the code below to start select2 on page load:

$(document).ready(function(){
   aplicaSelect2();
});

Finally, call the aplicaSelect2() function when adding a new line:

function clonarLinha() {
   if (x <= campos_max) {

       ...

       x++;
       aplicaSelect2();
   }
}

See it working:

var campos_max = 10;   //max de 10 campos
var x = 1;
function clonarLinha() {
   if (x <= campos_max) {
       $('#tabelaCorpo').append('<tr id="linhaClonada">\
         <td id="atualizarBolsista">\
              <select class="bolsista form-control" name="bolsista[' + x + ']"></select>\
         </td>\
          <td><label class="radio-inline">\
          <input type="radio" name="vinculo[' + x + ']" value="1">Bolsista</label>\
          <label class="radio-inline">\
          <input type="radio" name="vinculo[' + x + ']" value="2">Voluntário</label>\
         </td>\
         <td>\
             <div class=" col-lg-12">\
                 <select class="form-control" name="horas[0]">\
                     <option value="02:00:00">2</option> \
                     <option value="06:00:00">4</option>\
                     <option value="08:00:00">8</option>\
                     <option value="16:00:00">16</option>\
                 </select>\
             </div>\
         </td>\
         <td>\
             <input type="button" onclick="removerLinha(this)" class="btnX btn btn-danger" value="X">\
         </td>\
         </tr>');
       x++;
       aplicaSelect2();
   }
}

function aplicaSelect2(){
   $('.bolsista').select2({
      placeholder: 'Selecione um aluno',
      ajax: {
         url: '../php/ajaxSelectAluno.php',
         dataType: 'json',
         delay: 250,
         processResults: function (data) {
            return {
               results: data
            };
         },
         cache: true
      }
   });
}

$(document).ready(function(){
   aplicaSelect2();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><linkrel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script><divclass="form-group">
   <label class="control-label col-lg-4">Víncular Bolsistas:</label>
   <div class="control-label col-lg-9 col-lg-offset-1">
      <div class="form-horizontal">
         <div class="table-responsive">
            <table class="table table-bordered table-striped table-highlight">
               <thead>
                  <div class="row">
                     <th class="col-xs-5 col-sm-5 col-md-5 col-lg-5">Nome</th>
                     <th class="col-xs-4 col-sm-4 col-md-4 col-lg-4  ">Vinculo</th>
                     <th class="col-xs-2 col-sm-2 col-md-2 col-lg-2">Horas</th>
                     <th class="col-xs-1 col-sm-1 col-md-1 col-lg-1"></th>
                  </div>
               </thead>
               <tbody id="tabelaCorpo">
                  <tr id="linhaParaClonar">
                     <td>
                        <select class="bolsista form-control" name="bolsista[0]"></select>
                     </td>
                     <td>
                        <label class="radio-inline">
                        <input type="radio" name="vinculo[0]" value="1">Bolsista</label>
                        <label class="radio-inline">
                        <input type="radio" name="vinculo[0]" value="2">Voluntário</label>
                     </td>
                     <td>
                        <div class=" col-lg-12">
                           <select class="form-control" name="horas[0]">
                              <option value="02:00:00">2</option> 
                              <option value="06:00:00">4</option>
                              <option value="08:00:00">8</option>
                              <option value="16:00:00">16</option>
                           </select>
                        </div>
                        <!-- <input type="number" name="horas[0]" class="form-control" /> -->
                     </td>
                     <td>
                        <!-- <button onclick="removerLinha()" class="glyphicon glyphicon-remove"></button> -->
                     </td>
                  </tr>
               </tbody>
            </table>
            <div class="col-sm-offset-8">
               <input type="button" onclick="clonarLinha()" value="Adicionar" id="adcLinha" class="btn btn-success">
            </div>
         </div>
      </div>
   </div> 
</div>
</div>
</div>
<!--     </div> -->
<div class="row" id="box-cinza-inferior">
   <div class="col-lg-offset-1 col-sm-2">
      <a href="menu-extensao.php" class="btn btn-success" onClick="formVazio();">Voltar</a>
   </div>
   <div class="col-lg-offset-10" >
      <button type="submit" class="btn btn-success">Concluir</button>
   </div>
</div>
</form>
</div>
    
26.11.2017 / 20:23