Adding more input with jQuery

1

I have a simple form with 3 input. I need to enter a quantity in the input 'qtd', and so I need jQuery to multiply the table with the form, and change the 'name'.

Example;

If I enter 3 in the 'qtd' input will appear 3 tables with the following input: 'name1', 'name2', 'name3', 'sex1', 'sex2', 'sex3'.

Does anyone know how I can do this?

<input type='text' class='form_campos' name='qtd'>

<table>
  <tr>
    <td>
      <input type='text' class='form_campos' name='nome1'>
    </td>
    <td>
      <input type='text' class='form_campos' name='sexo1'>
    </td>
  </tr>
</table>
    
asked by anonymous 30.06.2016 / 13:26

2 answers

2

I think this is what you want:

$('input[name="qtd"]').on('keyup click', function(){
  var qtd = $(this).val();
  $('#inputs table').remove();
  if(qtd > 0) {
      var appending = '<table>';
      for(var i = 1; i <= qtd; i++) {
         appending += '<tr>\
                         <td>nome' +i+ ': \
                             <input type="text" class="form_campos" name="nome' +i+ '" placeholder="nome' +i+ '">\
                         </td>\
                         <td>sexo' +i+ ': \
                             <input type="text" class="form_campos" name="sexo' +i+ '" placeholder="sexo' +i+ '">\
                         </td>\
                       </tr>';
      }
      appending += '</table>';
      $('#inputs').append(appending);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="inputs">
  <input type="number" class='form_campos' name='qtd' min='0'>
</div>
    
30.06.2016 / 13:42
1

I got it this way, but without JQuery

function gera(){
var x = document.getElementById("qt").value;
 tab=document.getElementById("tables");
      tab.innerHTML='';
  for(i=1; i<=x ; i++)
    {
      
    tab.innerHTML+="<table><tr><td>Nome "+i+":<input type='text' class='form_campos' name='nome"+i+"'></td></tr><tr><td>Sexo "+i+":<input type='text' class='form_campos' name='sexo"+i+"'></td></tr></table>";
    }
  
}
<input type='text' class='form_campos' name='qtd' onkeyup="gera()" id="qt">

 

<div id="tables"></div>
    
30.06.2016 / 13:40