Home » Jquery » javascript – How to get a ID in a modal coming by dataTable?

javascript – How to get a ID in a modal coming by dataTable?

Posted by: admin February 22, 2020 Leave a comment

Questions:

My question is, I’m posting an ID into a modal, but when I click in a datepicker inside modal, it gives me as an undefined value, it seems that I’m losing the ID somewhere, could you help me? Here is my code:

Here is my modal HTML:

<div class="modal fade" id="modalUpdatePeriodico" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered " role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title">Prontuário médico</h4>
          <!-- para pegar o id do meu campo -->
          <input type="hidden" id="hiddenIdPeriodic"/>
        </div>
        <div class="modal-body">
          <div class="row">
            <!-- left column -->
            <div class="col-md-12">
                <!-- Inicio do Formulario de Pesquisa -->
                <form id="formUpdatePeriodico" enctype="multipart/form-data" action="#" method="POST">
                <!-- Form Data e Qtde dias -->
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label for="dateExam">Data da Realização</label>
                    <input type="text" class="form-control datepicker-calendar" id="dateExam" name="dateExam">
                  </div>
                  <div class="form-group col-md-6">
                    <label for="statusExam">Status</label>
                    <select class="form-control select2" id="statusExam" name="statusExam">
                      <option value="1">Inapto</option>
                      <option value="2">Apto</option>
                    </select>
                  </div>
                </div>
              </form>
              <!-- Fim do Formulario de Pesquisa -->
            </div>
            <!--/.col (right) -->
          </div>
          <!-- /.row -->
        </div>
        <div class="modal-footer">
          <button 
            type="button"
            id="btnSavePeriodic"
            class="btn btn-success" 
            data-dismiss="modal" 
            onclick="saveEmpRestrictions('periodics', inputMatriculaAtes, dateExam, statusExam, hiddenIdPeriodic, examType);">
            Salvar
          </button>
          <button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>
        </div>
      </div>
    </div>

Here is my DataTable JS code:

function tbPeriodic() {

    // Definição do id da tabela como um dataTable
      $("#tbPeriodico").DataTable({
          "ajax": "webservices/ws_medicalRecord/tables/tb_medicalRecords.php?action=per&matriculaOp=" + <?php echo $matricula; ?>,
          sorting: false,
          "columns": 
          [
              { "data": "id" ,
                render: function(data, type, row) { // Função para link de download dos arquivos que foram "upados" no formulário.
                  data = '<a href="#" data-toggle="modal" data-target="#modalUpdatePeriodico" data-id="' + row.id + '" id="' + row.id + '">' + row.id + '</a>';
                  return data;
                } 
              },
              { "data": "ult_exame" },
              { "data": "tipo_exame" },
              { "data": "status_exame" },
              { "data": "prox_exame" }
          ]         
      });
    }

Here is my function to post my id into a input hidden:

$("#modalUpdatePeriodico").on('show.bs.modal', function (event) {
        var callModal = $(event.relatedTarget); // Para pegar tudo que há na opção que chama o modal
        var id = callModal.data('id'); // pegando o parametro ID da minha opção que chama o modal (data-id)
        console.log(id);
        var modal = $(this); 
        modal.find('.modal-header #hiddenIdPeriodic').val(id); // Adicionando o id em um campo hidden só para pegar esse valor depois 
    });

Here is my datepicker function:

$('.datepicker-calendar').datepicker({
      autoclose: true
    });

So, when I input a date from my datepicker the console shows me undefined, could you help me?

Thanks a lot!

How to&Answer:

I think you are confused here and there are 2 things happening. Or I should say there is one thing happening and the other step is missing. I am going to try and clarify this for you.

#1

The undefined is happening because you are not getting the value of id correctly. Add a class clickme to your dataTable <a> like below and get rid of the modal call.

dataTable

data = '<a class="clickme" href="#" data-id="' + row.id + '" id="' + row.id + '">' + row.id + '</a>';

Then get rid of

$("#modalUpdatePeriodico").on('show.bs.modal', function (event) {
    var callModal = $(event.relatedTarget); // Para pegar tudo que há na opção que chama o modal
    var id = callModal.data('id'); // pegando o parametro ID da minha opção que chama o modal (data-id)
    console.log(id);
    var modal = $(this); 
    modal.find('.modal-header #hiddenIdPeriodic').val(id); // Adicionando o id em um campo hidden só para pegar esse valor depois 
});

and change it to

$(document).on('click', '.clickme', function() {
    var id = $(this).data('id');
    $('#modalUpdatePeriodico').modal('show');
    $('#modalUpdatePeriodico').find('#hiddenIdPeriodic').val(id);
    console.log(id);
})

#2

The date thing is a different event so add this to get the date

$('.datepicker-calendar').datepicker({
    autoclose: true,
    onSelect: function(date) {
        console.log(date)
    }
})