Button to insert new inputs into the form

3

I have a site that records building releases. Here some buildings have more than one tower, and I would like for each tower, I had the possibility to insert 4 inputs (type, footage, bedrooms, vacancies)

Something like this:

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

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

<form>
<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>
</form>
    
asked by anonymous 07.05.2018 / 18:13

1 answer

1

Doing this in Jquery you can add:

$('.addtorre').click(function(){
    $('form').append(
        '<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 .

  

Reference

Why did I remove <form> ?

The tag <form> here only served to represent the form, so there is no need to create a preventDefault() of the form, the removal of the tag already does the work, since the method of sending can be done in Jquery.Ajax() .

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

<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">
</div>

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

$('#addtorre').click(function(){
    var id = parseInt($(".torre").last().attr('id'))+1;
    alert(id);
    $('.form').append(
        '<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">'
    );
});
    
07.05.2018 / 18:24