Getting all form values by JavaScript
Here is a working fiddle in vanilla JavaScript, but you need to add a serialize utility function. This works exactly like $('form').serialize()
in jQuery.
JavaScript:
var data;
function serialize(form) {
if (!form || form.nodeName !== "FORM") {
return;
}
var i, j, q = [];
for (i = form.elements.length - 1; i >= 0; i = i - 1) {
if (form.elements[i].name === "") {
continue;
}
switch (form.elements[i].nodeName) {
case 'INPUT':
switch (form.elements[i].type) {
case 'text':
case 'hidden':
case 'password':
case 'button':
case 'reset':
case 'submit':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
case 'checkbox':
case 'radio':
if (form.elements[i].checked) {
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
}
break;
}
break;
case 'file':
break;
case 'TEXTAREA':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
case 'SELECT':
switch (form.elements[i].type) {
case 'select-one':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
case 'select-multiple':
for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
if (form.elements[i].options[j].selected) {
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
}
}
break;
}
break;
case 'BUTTON':
switch (form.elements[i].type) {
case 'reset':
case 'submit':
case 'button':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
}
break;
}
}
data = q.join("&");
}
And change your form onchange
to
<form onchange="serialize(this)">
I tested it and am getting "size=small&status=0"
in the console.
I guess this would be a nice ECMAScript 6 vanilla JavaScript-based solution.
const form = document.getElementById("sampleForm");
form.addEventListener("submit", e => {
e.preventDefault();
let reqBody = {};
Object.keys(form.elements).forEach(key => {
let element = form.elements[key];
if (element.type !== "submit") {
reqBody[element.name] = element.value;
}
});
submitForm(reqBody); // Call to function for form submission
});
I don't know if there is an easier wait to do this but this solution, using just ECMAScript, is working for me:
function getPlainObjectFromFormElement(form) {
const elements = form.elements;
return Object.keys(elements)
.reduce((obj, field) => {
if (isNaN(field)) {
obj[field] = elements[field].value;
}
return obj;
}, {});
}
document.querySelector("form").onsubmit = function (e) {
alert(JSON.stringify(getPlainObjectFromFormElement(e.target)));
}
For input fields you could use ECMAScript 6 like the following:
Get your form in a constant:
const form = document.querySelector('form')
Grab all values:
Object.values(form).reduce((obj,field) => { obj[field.name] = field.value; return obj }, {})
The above snippet will produce an object with the input name as the key and its value.