Pass the form element to the function, and iterate over its
elements
collection to build the text:
<form onsubmit="download(this['name'].value, this)">
function download(filename, form) {
var lines = [];
var elements = form.elements;
for (var i = 0; i < elements.length; i++) {
var field = elements[i];
if (!field.name) { continue; }
switch (field.type) {
case "radio":
case "checkbox": {
if (field.checked) {
lines.push(field.name + ": " + field.value);
}
break;
}
default: {
lines.push(field.name + ": " + field.value);
break;
}
}
}
var text = lines.join("\n");
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
Demo[
^]