How to clone an element with jQuery and add a new name?

7

I'm using the jQuery CloneYa plugin. to clone elements of a form with jQuery, but it is a bit limited, I wanted to clone the inputs but I need to increment the name when done, for example:

<input type="text" name="produtos[qtd][1]">

The next input cloned would have to have the name produtos[qtd][2] , if there is a way to do this with this plugin or otherwise, the consequence of cloning the inputs is that the validation plugin only validates the first input ( jquery.validate ).

This is an example of how my form is

<form method="post">
    <div class="wrapper">
        <div class="toclone">
            <select name="list">
                <option>selecione...</option>
                <option>opção 1</option>
                <option>opção 2</option>
                <option>opção 3</option>
                <option>opção 4</option>
            </select>
            <input type="text" name="produtos[qtd][]">
            <button type="button" id="add">+</button>
            <button type="button" id="remove">-</button>
        </div>        
    </div>
    <input type="submit">
</form>

JSFiddle

    
asked by anonymous 17.03.2014 / 15:36

1 answer

6

To clone your element, and set the name to the previous name with a +1 value, simply do as follows:

function adicionar(){
  var ElementoClonado = $(this.parentNode).clone(); //clona o elemento
  var str = $(ElementoClonado).children('input').eq(0).attr('name').split("["); //divide o name por "["
  console.log(str);
  var intQtd = parseInt(str[2].split("]")[0]); //resgata o numero entre "[" e "]"
  console.log(intQtd);
  var newName = "produtos[qtd]["+(intQtd+1)+"]"; //novo valor name somado +1 do original
  ElementoClonado.children('input').eq(0).attr('name', newName); //seta o novo name para o elemento clonado
  $('.wrapper').append(ElementoClonado);
  $('.add').on("click", adicionar);
  $('.remove').on("click", remover);
  $(this).unbind("click");
}
function remover(){
  $(this.parentNode).remove();
}
$('.add').on("click", adicionar);
$('.remove').on("click", remover);

However, you should remember that you can not have more than one HTML ID equal, so change all your html to use classes, and you should also start with the number 1 of "qtd" like this:

<form method="post">
<div class="wrapper">
    <div class="toclone">
        <select name="list">
            <option>selecione...</option>
            <option>opção 1</option>
            <option>opção 2</option>
            <option>opção 3</option>
            <option>opção 4</option>
        </select>
        <input  type="text" name="produtos[qtd][1]">
        <button type="button" class="add">+</button>
        <button type="button" class="remove">-</button>
    </div>        
</div>
    <input type="submit">
    </form>

Example running in JSFiddle

    
17.03.2014 / 15:55