0

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.

  • 2
    See https://javascript.info/formdata , it will take form element and get all values at once. and then convert to JSON: https://stackoverflow.com/questions/41431322/how-to-convert-formdata-html5-object-to-json – ikiK Jun 25 '21 at 13:59
  • 1
    Indeed, FormData already does that, I think you are reinventing the wheel – Jeremy Thille Jun 25 '21 at 14:02
  • You could have a single loop over `form.elements`, but you'd still need to switch on the element type in that loop. – Bergi Jun 25 '21 at 14:27
  • Thank you guys, formdata did the trick! – purple_AUT Jun 28 '21 at 15:42

0 Answers0