datepicker does not work in dynamic form with Js

1

Well, I've assembled a dynamic form using JS. Within this form I have several input with class data , where I call the datepicker. But they do not work, can anyone help me with this?

Follow the example below. Note that in non-dynamic input the datepicker works.

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


function adicionarCampos() {
    var objSelect = document.getElementById("numParcelas");
    var i;
    var linha = "";


    // Cria os input
    for (i = 0; i < objSelect.value; i++) {

      // Monta HTML
      linha += "\
                <input type='text' name='data" + i + "' id='linha" + i + "' class='data' maxlength='10'>\n\
            ";

    }
    document.getElementById("txtParcelas").innerHTML = linha;
  }
  // Chama o evento
window.onload = adicionarCampos;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>

Aqui o datepicker funciona
<input type='text' class='data'>

<br><br><br><br>


Gera o formulário
 <input type='text' id='numParcelas' name='numParcelas' OnKeyUp="adicionarCampos()" value="1">
  <br>
Aqui o datepicker não funciona<br>
<span id="txtParcelas"></span>
    
asked by anonymous 11.08.2016 / 15:39

2 answers

2

You need to re-bind the new element. Look at the example below:

function FazBind() {
$('.data').datepicker({
  'autoclose': true
});
}

function adicionarCampos() {
    var objSelect = document.getElementById("numParcelas");
    var i;
    var linha = "";


    // Cria os input
    for (i = 0; i < objSelect.value; i++) {

      // Monta HTML
      linha += "\
                <input type='text' name='data" + i + "' id='linha" + i + "' class='data' maxlength='10'>\n\
            ";

    }
    document.getElementById("txtParcelas").innerHTML = linha;
FazBind() 
  }
  // Chama o evento
window.onload = adicionarCampos;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>

Aqui o datepicker funciona
<input type='text' class='data'>

<br><br><br><br>


Gera o formulário
 <input type='text' id='numParcelas' name='numParcelas' OnKeyUp="adicionarCampos()" value="1">
  <br>
Aqui o datepicker não funciona<br>
<span id="txtParcelas"></span>

UPDATING:

To better explain, loading the page assembles binds between HTML components and JS functions. When adding some element you need to tell the person who processes that there are new elements with new binds. I created a function to mount the bind you made from the data classes, and call it every time I add a new field.

    
11.08.2016 / 15:45
0

This is a JavaScript feature, #, in an extremely similar case.

11.08.2016 / 15:49