It smells like a trivial one but can't figure it out. I have a html form that is generated dynamically by JS and filled with initial data grabbed from server, DB passed as a parameter to displayResForm. The form is displayed correctly with filled data. Now I want to be able to modify this data through this form and POST it back to DB as JSON format but the problem is I am not able to capture the html form data in my JavaScript.
The form base is as follows:
<form method="POST" id="res-form" name="modForm" onSubmit="modSubmit()">
{% csrf_token %}
</form>
and it gets built with:
function displayResForm(results) {
var form = document.getElementById("res-form");
for (var i = 0; i < results.length; i++) {
var input = document.createElement("input");
input.setAttribute("type", "number");
input.setAttribute("value", results[i][1]);
input.setAttribute("id", toString(i));
var label = document.createElement("label");
label.setAttribute("for", toString(i));
label.appendChild(document.createTextNode(results[i][0]));
form.appendChild(label);
form.appendChild(input);
form.appendChild(document.createElement("br"));
}
var mod = document.createElement("input");
mod.setAttribute("class", "btn btn-info");
mod.setAttribute("type", "submit");
mod.setAttribute("value", "Modify");
mod.setAttribute("onclick", "modSubmit()");
form.appendChild(mod);
}
As you can see I have two calls of modSubmit (one in form tag, the other in submit button) but neither works.
And I want to grab it (to send POST request to server, not implemented yet):
function modSubmit() {
//var formData = JSON.stringify($("modForm").serializeArray());
var formData = $('modForm').serializeArray()
console.log("formData=", formData);
alert(formData);
// todo POST back to server
return false;
}
The issue is I keep on getting empty formData ...
EDIT:
I can easily get the value of elements manually by
var x = document.getElementById("res-form");
var el = x.elements[1].value;
alert(el);
But I hoped for one-liner.