php – Button to insert new inputs into the form


I have a website that registers building releases. Then some buildings have more than one tower, and I would like that for each tower, I had the possibility to insert 4 inputs (type, footage, bedrooms, spaces)

Something like this:

<input type="text" name="torres"><button id="addtorre">Adicionar Torre</button>
<button type="submit">Cadastrar</button>

Then if you put 2 in the "towers" field and click on "Add Tower" , it would be:

<input type="text" name="torres"><button id="addtorre">Adicionar Torre</button>
<input type="text" name="tipo1">
<input type="text" name="metragem1">
<input type="text" name="dorm1">
<input type="text" name="vaga1">
<input type="text" name="tipo2">
<input type="text" name="metragem2">
<input type="text" name="dorm2">
<input type="text" name="vaga2">
<button type="submit">Cadastrar</button>


By doing this in Jquery you can add:

        '<input type="text" name="tipo[]">'+
        '<input type="text" name="metragem[]">'+
        '<input type="text" name="dorm[]">'+
        '<input type="text" name="vaga[]">'

Fields become arrays when passed to PHP .


Why did I remove the <form> ?

The <form> tag here was only meant to represent the form, so there is no need to create a form's preventDefault() , removing the tag already does the work, since the submission method can be done in Jquery.Ajax() .

Here in HTML added the id attribute to the <input> tags and the class="torre" :

<div class="form">
    <input type="text" name="torres"><button id="addtorre">Adicionar Torre</button>
    <button type="submit">Cadastrar</button>
    <input type="text" name="tipo" id="1" class="torre">
    <input type="text" name="metragem" id="1" class="torre">
    <input type="text" name="dorm" id="1" class="torre">
    <input type="text" name="vaga" id="1" class="torre">

In Jquery , by clicking on the <button> "Add Tower", the last value of the id is searched, added 1 and then we have the id of the new tower, then we do append() inside the <div class="form"> of the same:

    var id = parseInt($(".torre").last().attr('id'))+1;
        '<input type="text" name="tipo" id="'+id+'" class="torre">'+
        '<input type="text" name="metragem" id="'+id+'" class="torre">'+
        '<input type="text" name="dorm" id="'+id+'" class="torre">'+
        '<input type="text" name="vaga" id="'+id+'" class="torre">'
Scroll to Top