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

Asked

Viewed 156 times

0

The script below adds groups of fields in a form. So far ok. Fields are added but when I send the form I only receive data from fixed inputs, which 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--;
  })
});

1 answer

1

The problem can be solved simply.

Jquery takes and stores all elements of the page at the moment it is loaded, so when we create a new element dynamically it does not exist in the stored memory of Jquery agrees ? (If you don’t just accept, that’s how it works haha).

Well, to get around that 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 assume that when you click on a button the dynamically generated div changes, follow the example:

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

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

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

That way we have to go through all the elements until we reach a father who already existed in the document, follows the example:

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

Thus the class .dinamicamenteGerado4 daughter of other dynamic elements may be changed!

This technique serves for any dynamically generated element!

Browser other questions tagged

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