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

Asked

Viewed 166 times

2

I happen to have the following situation, in my HTML I have the structure that 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" the code in jQuery clones and repeats this excerpt just below, follows the code in jQuery:

$( "#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 piece of cloned code, that is, equal, to have the attribute name="produto0" different, for example name="produto1", how to do this using the jQuery?

1 answer

2


After cloning the element, you count how many exist and change the attribute name 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);      
});
  • I think your Cód. just missed the part that counts, the "0" over there select[name^='produto'], that is, like: select[name^='produto0']. It all worked out, thanks. If you edit where I showed you to look exactly like Cód. HTML that I put in, let other people get lost in it!

  • No, you can’t have 0. :D

  • Mine worked with the zero there, ta I will see well! ;)

  • It may work too, but then you have to change tb here by putting a zero: .attr("name", "produto0"+conta);

  • Okay, perfect, you saved me! D

Browser other questions tagged

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