Input added with .append () does not send the POST data

0

The script below adds groups of fields to a form. Until then, okay. The fields are added but when I send the form I only receive the data from the fixed inputs, those that are added dynamically are not received.

Code:

$(document).ready(function() {
  var max_fields = 100; //maximum input boxes allowed
  var wrapper = $(".input_fields_wrap"); //Fields wrapper
  var add_button = $(".add_field_button"); //Add button ID
  var token = $('#token').val();
  var x = 1; //initlal text box count
  
  $(add_button).on({click: function(e){ //on add input button click
    e.preventDefault();
    var length = wrapper.find("input:text").length;
    if (x < max_fields) { //max input box allowed
      x++; //text box increment
      $(wrapper).append('ADD INPUTS'); //add input box
    }

    wrapper.find("input:hidden").each(function() {
      $(this).val()
    });
    
    $(function (){
    $('.select2').select2()
    });

  }});
 
  $(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
    e.preventDefault();
    $(this).parent('div').remove();
    x--;
  })
});
    
asked by anonymous 24.10.2017 / 16:18

1 answer

1

The problem can be solved simply.

Does Jquery receive and store all the elements of the page at the time it is loaded, so when we create a new element dynamically it does not exist in the stored memory of Jquery do you agree? (if you do not agree just accept it, this is how haha works) .

Well, to get around this situation, we have to indicate the parent element of this new dynamically created element. Remember that the parent element should already exist at the time of page loading.

Let's suppose that when you click a button the dynamically generated div undergoes change, the example follows:

$('.jaExisto').on('click', '.dinamicamenteGerado', function(){alert('Olá Mundo')});

You are telling Jquery that it is to perform a given function on the child of an element that already existed on the page!

What if your dynamic element is the child of another dynamic element?

In this way we will have to go through all the elements until we reach a parent that already existed in the document, follow the example:

 $('.jaExisto').on('click', '.dinamicamenteGerado1 .dinamicamenteGerado2 .dinamicamenteGerado3 .dinamicamenteGerado4', function(){alert('Olá Mundo')});

In this way the .dinamicamenteGerado4 class that is the child of the other dynamic elements can be changed!

This technique is for any dynamically generated element!

    
24.10.2017 / 17:46