Insertion of dimly created inputs

0

I'm dynamically creating fields 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, I now do not know how to enter these fields in the database, as they will vary. I accept suggestions!

    
asked by anonymous 09.06.2017 / 03:30

1 answer

1

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

To do this, add [] after the name tag 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[]" />');
      }

    });

});
  

PHP example of how to recover:

<?php

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

To save to 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 repeat the amount of information that the field was inserted with several inserts.

If you want to study a little about Data Modeling, I'll leave it as a hint at the Bradesco site there several free courses and one of them is about database modeling.

    
09.06.2017 / 03:37