In JavaScript è possibile serializzare i valori di un form in molti modi. Di seguito vedremo come serializzare tali valori come una stringa JSON.
Gli elementi che ci interessano sono quelli provvisti di un attributo name
. Ecco la soluzione:
(function() {
const formToJSONString = form => {
if(form === null || !form) {
return '';
}
let data = {};
const elements = form.querySelectorAll('input[name], select[name], textarea[name]');
elements.forEach(element => {
let { name, value } = element;
data[name] = value;
});
return JSON.stringify(data);
};
})();