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

Asked

Viewed 112 times

1

How can I make a form where you have a text pad of type number, and according to the number I enter appears groups of text box to fill in this same 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 without doing refresh to the page, and in the end send all form inckuido to day number text box I am working with php (Codeigniter)

1 answer

2


Using jQuery you can make a loop for and create as many inputs as you need. See 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>
<input type="text" id="txtQuantidade" />
<input type="button" id="btnAdicionar" value="Adicionar" />
<div id="divForm"></div>

Browser other questions tagged

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