PhasedEvolution PhasedEvolution - 1 month ago 5
HTML Question

Can't get form from a dynamically created form

I have a button that makes a form appear in my html page. I have a function that gets the 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 seems to work well because I can get the data from other forms that weren't dynamically created. I create my form this way by clicking a 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 another button that should is responsible for getting the 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 a experienced programmer so sorry for any mistakes...

Answer

Do you have a reason to use the mix of pure js and jquery? JQuery form creating can help you.

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/

Update

The mix works too if you append an input and define 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/

Comments