How to add groups of inputs according to the number inserted in a text box without refresh

1

How can I make a form that has a box of text type number, and according to the number that I enter appears groups of text box to fill in that form?

Example:

Text box (number of days) = 4

<div>
<input type="date" name="data[]">
<input type="time" name="hinicio[]">
<input type="time" name="hfim[]">
</div>

<div>
<input type="date" name="data[]">
<input type="time" name="hinicio[]">
<input type="time" name="hfim[]">
</div>

<div>
<input type="date" name="data[]">
<input type="time" name="hinicio[]">
<input type="time" name="hfim[]">
</div>

<div>
<input type="date" name="data[]">
<input type="time" name="hinicio[]">
<input type="time" name="hfim[]">
</div>

Another example:

Text box (number of days) = 1

<div>
<input type="date" name="data[]">
<input type="time" name="hinicio[]">
<input type="time" name="hfim[]">
<div>

This does not refresh the page, and in the end send all the form inckuido the text box number days I'm working with php (Codeigniter)

    
asked by anonymous 03.12.2015 / 17:07

1 answer

2

Using jQuery you can loop for and create as many inputs as you need. Here's an example:

$(document).ready(function() {
  var $txtQuantidade = $('#txtQuantidade');
  var $btnAdicionar = $('#btnAdicionar');
  var $divForm = $('#divForm');

  $btnAdicionar.on('click', function() {
    var qtde = $txtQuantidade.val();
    console.log(qtde);
    var html = '';

    for (var i = 0; i < qtde; i++) {
      html += '<div>';
      html += '<input type="date" id="txtData_' + i + '" name="data[]">';
      html += '<input type="time" id="txtHoraIni_' + i + '" name="hinicio[]">'
      html += '<input type="time" id="txtHoraFim_' + i + '" name="hfim[]">';
      html += '<div>';
    }

    $divForm.html(html);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="txtQuantidade" />
<input type="button" id="btnAdicionar" value="Adicionar" />
<div id="divForm"></div>
    
03.12.2015 / 17:17