Timepicker in jquery dynamic input

Asked

Viewed 172 times

0

Needed to add the datepicker plugin to inputs that are added dynamically via a jquery script:

Follow 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 to the class of the date text boxes:

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

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

1 answer

1


you will need to call the plugin manually after including the elements on 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.

Browser other questions tagged

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