Timepicker in dynamic input jquery

0

I needed to add the datepicker plugin to inputs that are added dynamically through a jquery script:

Here is the script I'm using:

$(document).ready(function() {

var txtQuantidade = document.getElementById("txtNumDias");
var divForm = document.getElementById("divForm");
var tmplLinha = document.getElementById("tmplLinha").content;

txtQuantidade.addEventListener("change", function () {
var quantidade = {};
quantidade.old = parseInt(divForm.dataset.qtd) || 0;
quantidade.new = parseInt(txtQuantidade.value) || 0;

if (quantidade.new > quantidade.old) {
for (var indice = quantidade.old; indice < quantidade.new; indice++) {
  var linha = document.importNode(tmplLinha, true);
  [].forEach.call(linha.querySelectorAll("input[id]"), function (input){    
    input.id = input.id + indice;
  });
  divForm.appendChild(linha);
}
} else {
var linhas = [].slice.call(divForm.children, quantidade.new);
linhas.forEach(function (linha, indice) {
  divForm.removeChild(linha);    
});
}
divForm.dataset.qtd = quantidade.new;
});
}).trigger('onchange');

This script adds the number of inputs that is defined in a text input, depending on the number, creates the following code

                                 <div id="divForm"></div> 
                                        <template id="tmplLinha">
                                        <div class="col-md-12">
                                        <div class="col-md-4">    
                                           Dia: <input type="text"        class="inserir_data form-control" name="data[]" value=""/>

                                        </div>
                                        <div class="col-md-4">
                                           Hora de Inicio: <input type="time" class="form-control" name="hinicio[]" value="<?php echo set_value('hinicio[0]'); ?>"/> 
                                        </div>
                                        <div class="col-md-4">   
                                           Hora fim: <input type="time" class="form-control" name="hfim[]" value="<?php echo set_value('hfim[0]'); ?>"/><br/>
                                        </div> 
                                         </div>
                                        </template>

follows the script to call the function for the class of the date text boxes:

$(function() {
$('.inserir_data').datepicker();
});

I already tried to create a text box outside of this dynamic content and everything works but these text boxes do not work

    
asked by anonymous 11.03.2016 / 18:52

1 answer

1

You will need to call the plugin manually after adding the elements to the page:

.
.
.
divForm.appendChild(linha);
$('.inserir_data', linha).datepicker();
.
.
.

Note that I am using the variable linha as [context] , this is necessary to avoid unnecessary processing.

    
11.03.2016 / 19:10