Unable to get form from dynamically created form

I have a button that displays a form on my html page. I have a function that gets data from forms:

function getFormData($form){

   var unindexed_array = $form.serializeArray();

   var indexed_array = {};

   $.map(unindexed_array, function(n, i){

      indexed_array[n['name']] = n['value'];

   });

   return indexed_array;

}

The function works well, because I can get data from other forms that were not dynamically created. I create my form this way by clicking the button:

var new_form = document.createElement('form');
new_form.id = "new_form";

// (...) all the inputs for the form

// and I append to an existent div 
existent_div.appendChild(new_form);
// and then the inputs
new_form.appendChild(input1); (...)

I have one more button which should be responsible for receiving form data. It calls this function, and in the middle of the function I have this:

var new_form_info = getFormData($("#new_form"));
// I get an empty object... 

Why is this happening? I am not an experienced programmer, so sorry for any errors ...

+4
source share
1 answer

js jquery? JQuery .

var new_form = $('<form></form>')
        .attr('id', "new_form")
        .append('<input type="text" value="1" name="inp" />');    
$('#existent_div').append(new_form);
console.log($('#new_form').serializeArray());

https://jsfiddle.net/yej5xc8s/

, existent_div

function getFormData($form){
   var unindexed_array = $form.serializeArray();
   var indexed_array = {};
   $.map(unindexed_array, function(n, i){
      indexed_array[n['name']] = n['value'];
   });

   return indexed_array;
}

var new_form = document.createElement('form');
new_form.id = "new_form";
var input = document.createElement('input');
input.name = "qwer";
input.value = "1";
new_form.appendChild(input);

var existent_div = document.getElementById('existent_div');
existent_div.appendChild(new_form);

console.log(getFormData($("#new_form")));

https://jsfiddle.net/yej5xc8s/1/

+1

Source: https://habr.com/ru/post/1656789/


All Articles