Insertion of dimanically created inputs

Asked

Viewed 18 times

0

I’m creating fields dynamically like this:

$(document).ready(function(){

    $('#quantidade').on('change', function(){

      var quantidade = $('#quantidade').val(),
          campos = $('#campos');

      campos.html(''); //aqui eu fiz limpar a div
      for (x = 0; x < quantidade; x++) {
        campos.append('<input type="text" id="campo-'+x+'" />');
      }

    });

});

However, now I do not know how to insert these fields in the bank, as they will vary. I accept suggestions!

1 answer

1


Well I believe your question is how to recover this in PHP is this?

To do this add [] after the tag name of your input.

I’ll leave an example:

$(document).ready(function(){

    $('#quantidade').on('change', function(){

      var quantidade = $('#quantidade').val(),
          campos = $('#campos');

      campos.html(''); //aqui eu fiz limpar a div
      for (x = 0; x < quantidade; x++) {
        campos.append('<input type="text" id="campo-'+x+'" name="campo[]" />');
      }

    });

});

Example in PHP of how to recover:

<?php

for($i = 0; $i < count($_POST['campo']; $i++) {
    echo "Campo $i = " . $_POST['campo'][$i];
}

To save in the database you can make use of a table 1 for N, where in this table you put the id of the main information and repeats the amount of information that the field was inserted with multiple Inserts.

If you want to study a little about Data modeling I leave as a hint the site of the foundation Bradesco there are several free courses and one of them is about database modeling.

  • Thank you, it worked properly.

Browser other questions tagged

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