Reputation: 21
I have multiple questions in a form and I am trying to append each answer to an empty object:
const y = document.createElement("INPUT");
y.setAttribute("class", "textBox");
y.setAttribute("id", "fourthQID");
window.data.appendChild(y);
for (const o of i.options){
const x = document.createElement("INPUT");
x.setAttribute("type", "radio");
x.setAttribute("id", "radioID");
x.name = "RadioBtn";
x.value = o;
const y = document.createElement("LABEL");
const t = document.createTextNode(o);
y.appendChild(t);
const div = document.createElement("div");
div.style.height = "5px";
div.appendChild(x);
div.appendChild(y);
document.getElementById("radioButton").appendChild(div);
window.data.appendChild(x);
window.data.appendChild(y);
window.data.appendChild(div);
}
const answers = [];
const data = {"answers": []};
const fourthQuestion = JSON.stringify(document.getElementById('fourthQID').value);
const fifthQuestion = JSON.stringify(document.querySelector("input[name=RadioBtn]:checked").value);
I have tried this, but it doesn't seem to work:
answers.push(firstQuestion);
answers.push(secondQuestion);
data.answers.push(firstQuestion);
data.answers.push(secondQuestion);
How can I get the answers from the form as a JSON in answers = []
?
Upvotes: 0
Views: 2380
Reputation: 453
To append each answer to an empty object try Object.assign().
// The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.
const returnedTarget = Object.assign(target, source);
Better solution is to use FormData(). For example:
// get form values
const myForm = document.forms.FORM_NAME_ATTRIBUTE;
// init new FormData() object
const formData = new FormData();
// Add form elements to formData object
[...myForm.elements].forEach((element) => {
if (element.name.length > 0) {
formData.append(element.name, element.value);
}
});
// or use formData.append() to add elements
formData.append(el.name, el.value);
// and then stringify FormData
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);
Upvotes: 1