I am currently working on a piece of JavaScript that should generate a JSON object from as many types of inputs, selects, etc. by retrieving the name property as key and the value of the input as value.
I was wondering if there is a fancier way of achieving this than in the code snippet below.
function generateJson() {
var resultJsonString = {};
var selects = document.getElementsByClassName("SelectClass");
var inputs = document.getElementsByClassName("InputClass");
var checkboxes = document.getElementsByClassName("CheckboxClass");
for (var i = 0; i < selects.length; i++) {
resultJsonString[selects[i].getAttribute("name")] = selects[i].options[selects[i].selectedIndex].text;
}
for (var i = 0; i < inputs.length; i++) {
resultJsonString[inputs[i].getAttribute("name")] = inputs[i].value;
}
for (var i = 0; i < checkboxes.length; i++) {
resultJsonString[checkboxes[i].getAttribute("name")] = checkboxes[i].checked;
}
return JSON.stringify(resultJsonString);
}
As you can see I have to make dozens of lists and loop through them all since gathering the value doesn't work the same across different kinds of inputs and the like. I would like to reduce the number of lists and for loops I have to create.
If you need more details, I am happy to supply them.