How to repeat the fields of a form?

Asked

Viewed 1,962 times

1

I have a form where you have:

=f.input :name     , label: false , placeholder: "Nome do amigo"      , input_html:{class: "form__input"} , required: true

=f.input :email    , label: false , placeholder: "Email do amigo"     , input_html:{class: "form__input"} , required: true

Next door has an icon +, where if the user clicks on it, the two fields (name and email) appear empty below once again for a new registration. Somebody help me do this?

  • 1

    Welcome to Stackoverflow site. Post your code using code formatting, so it is more readable.

  • Is your code posted complete? Check so we can help.

  • If you posted a code it would help us understand the doubt. I understood that there are two inputs. But it was not clear to me what the "+" would do.

  • It’s an icon to add another friend

  • When someone clicked on the "+" again the same fields appear below...

  • 1

    You want to add fields dynamically ?

  • Exactly that

Show 2 more comments

4 answers

2

You can put the elements you want to clone inside a fieldset, thus:

<fielset id="group">
    <label for="nome">Nome do amigo</label>
    <input type="text" required classs="form__input" name="nome"/>

    <label for="email">E-mail do amigo</label>
    <input type="text" required classs="form__input" name="email"/>
</fielset>

Javascript:

var n = 0;
function addNovo(){
    var element = document.getElementById("group")
    var copy= document.cloneNode(element);
    n++;

    copy.getElementsByTagName('label')[0].htmlFor= 'nome'+n;
    copy.getElementsByTagName('input')[0].id= 'nome'+n;
    copy.getElementsByTagName('label')[1].htmlFor= 'email'+n;
    copy.getElementsByTagName('input')[1].id= 'email'+n;

    element.parentNode.appendChild(copy);   
}

Then just put in the event click function call onclick="addNovo() on its button that contains the +.

0

You can use javascript for this. When you click the button, you can do it (it’s just an example, you have to adapt to your code):

function add() {
    var x = '<input type="text" placeholder: "Nome do amigo" required /> <input type="text" placeholder: "Email do amigo" required />'; // colocar código html aqui.
    document.getElementById('id_form').innerHTML += x; // id_form id do seu formulário.
}

Then, just modify the add() function to adapt it to your code. Put an id to your form. This add() function will be called on the onclick button "+".

0

See if it fits you.

var counter = 1;
jQuery('a.add-author').click(function(event){
    event.preventDefault();
    counter++;
    var newRow = jQuery('<tr><td><input type="text" name="first_name' +
        counter + '"/></td><td><input type="text" name="last_name' +
        counter + '"/></td></tr>');
    jQuery('table.authors-list').append(newRow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<table class="authors-list">
  <tr><td>author's first name</td><td>author's last name</td></tr>
  <tr><td><input type="text" name="first_name" /></td><td><input type="text" name="last_name" /></td></tr>
</table>
<a href="#" title="" class="add-author">Add Author</a>

0

I built this bootstrap-based fiddle

http://jsfiddle.net/gildonei/ougkLo46/

HTML

<form id="form-teste">
  <div class="row clone">
    <div class="col-xs-12 col-sm-12 col-lg-5 col-md-5">
      <label for="PessoaEmail0EmailTipoId">Tipo de E-mail</label>
        <select name="data[PessoaEmail][0][email_tipo_id]" required="required" id="PessoaEmail0EmailTipoId" class="form-control">
          <option value="">Tipo de email</option>
          <option value="1">Pessoal</option>
          <option value="2" selected="selected">Profissional</option>
        </select>
    </div>
    <div class="col-xs-12 col-sm-12 col-lg-6 col-md-6">
        <label for="PessoaEmail0DsEmail">Endereço de E-mail</label>
        <input name="data[PessoaEmail][0][ds_email]" placeholder="Email" maxlength="255" required="required" class="email valid form-control" type="email" id="PessoaEmail0DsEmail"><i></i>
    </div>
    <div class="col-xs-12 col-sm-12 col-lg-1 col-md-1">
    <label>&nbsp;</label>
      <button type="button" title="remover" class="btn button-remove btn-danger col-md-12">
        <i class="fa fa-remove"></i>
      </button>
    </div>
  </div>
  <div class="row">&nbsp;</div>
  <div class="row">
    <div class="col-xs-12 col-sm-12 col-lg-12 col-md-12">
      <button type="button" class="btn button-more btn-success pull-right">
        <i class="fa fa-plus-circle"></i> Mais
      </button>
    </div>
  </div>
</form>

JAVASCRIPT

var nrQtdProduto = 0;
$(function() {

  $('.button-more').click(function() {
    var $objDivProduto = $(this).parent().parent().parent().children('.clone');
    nrQtdProduto = $(this).parent().parent().parent().children('.row').length - 1;

    $objDivProduto
      .clone()
      .removeClass('clone')
      .find('input:text, input.email').each(function(k, v) {
        var strName = $(v).attr('name');
        var strId = $(v).attr('id');

        $(this)
          .attr('name', strName.replace(0, nrQtdProduto))
          .attr('id', strId.replace(0, nrQtdProduto));

        if ($(this).attr('type') != 'hidden') {
          $(this).val('');
        }

      })
      .end()
      .insertAfter($objDivProduto);

    removeElement();
  });

});

function removeElement() {
  // -------------------------------------------------------
  // INICIO DO CÓDIGO DE REMOVER NOVO TELEFONE, EMAIL ...
  // -------------------------------------------------------
  $('.button-remove').click(function() {

    nrQtdProduto = $(this).parent().parent().parent().children('.row').length - 1;

    if (nrQtdProduto == 1) {
      showAlert('Erro', 'Você deve ter ao menos um campo para cadastro.');

      return;
    }

    if (confirm('Deseja realmente remover a linha ?')) {
      var objRemove = $(this).parent().parent();
      objRemove.hide("slow");
    }
  });
}

Browser other questions tagged

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