Change the values of the "name" attributes of subsequent html inputs / selects?

2

I happen to have the following situation, in my HTML I own the structure this way:

<div class="form-row mt-3">
   <select name="produto0" class="form-control{{ $errors->has('produtos') ? ' is-invalid' : '' }}">
      @foreach($produtos as $p)
      <option value="{{$p->id}}">{{$p->nome}}</option>
      @endforeach
   </select>
</div>
<a href="javascript:void(0)" class="btn btn-sm text-white bg-info" id="adicionar">
   <i class="fa fa-plus-square"></i> ADICIONAR NOVO PRODUTO</span>
</a>

And then when I click on the button that has the id="adicionar" code in jQuery clone and repeat that snippet below, follow the code in jQuery :

p>
$( "#adicionar" ).click(function(e) {
   e.preventDefault();
   var original = $(this).closest(".form-row");
   var copia = original.clone(true, true);
   original.after(copia);      
});

After that I would like the next clone code, that is equal, to have the name="produto0" attribute, for example name="produto1" , how to do this using jQuery p>     

asked by anonymous 04.12.2018 / 13:39

1 answer

2

After cloning the element, you count how many there are and change the attribute name by concatenating the value:

$( "#adicionar" ).click(function(e) {
   e.preventDefault();
   var original = $(this).closest(".form-row");
   var copia = original.clone(true, true);
   // conta quantos selects possuem name começando com "produto"
   var conta = $(".form-row select[name^='produto']").length;
   // busca o select no elemento clonado e altera o name
   copia.find("select").attr("name", "produto"+conta);
   original.after(copia);      
});
    
04.12.2018 / 14:01