How to use a cont variable p/ create an array of Names in input’s?

Asked

Viewed 43 times

0

I have a button where I can add fields to my form, and I need each new field to have a different name, I thought of using name = "products[]", and so create an array and use a foreach on the back, for example. Can you help me with this concatenation? I’ve tried a few times and I couldn’t.

This is the function responsible for cloning the fields. the idea was to make name="products[cont]" and in others as well, how to do? I know that in this way, whenever I call the function, the value of cont will again be 1, suggestions of how to keep cont constant and how to Zera it after sending the form, please.

     $(function () {
      var srcDiv = $('#dinamicDiv');
      var cont = 1;
      $(document).on('click', '#addInput', function(){
          $('<p>'+
              '<label for="Produto" id="Produto" class="col-form-label">Nome do produto: </label>' +
              '<button id="removeInput" class="btn-danger btn-add">Remover produto</button>' +
              '<input type="text" class="form-control" name="produtos[]">' +
              '<label for="Preço" id="Preço" class="col-form-label">Preço do produto:</label>' +
              '<input type="text" class="form-control" name="preços[]">' +
             '</p>').appendTo(srcDiv);
          cont ++;
          return false;
      });
  • I put it on Jsfiddle to make it better understood: https://jsfiddle.net/Jaozim/5xj0tbrp/3/

  • Zeroing this is done alone by the code itself if you do not store it in a Cookie for example, and when the sum of your var contains, you should use it like this: cont = cont++;

1 answer

0

There is no need to declare the position of the array in the element unless you want it to occupy a specific position.

In the following example, in your backend you will receive the array ["foo", "bar", "Baz"]:

<form>
    <input name="inp[]" value="foo">
    <input name="inp[]" value="bar">
    <input name="inp[]" value="baz">
</form>

Now if you want to declare the position manually, just have the counter started outside the scope of your Event Listener. In fact you are already doing this, just need to concatenate the cont in HTML, and Zera it after you submit your form.

  • Thanks for the help. I know I just need to concatenate, that’s the question, how to do it...?

Browser other questions tagged

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