Modelesq
Modelesq

Reputation: 5382

Loop through form inputs and store data in object

I'm just trying to create a javascript object.

const data = {};

// loop through each input found in form
$('#form_name').filter(':input').each(function() {
  const $id = $(this).attr('id');
  const $value = $(this).attr('value');
  data[$id] = $value;
  return data;
});

Checkout this fiddle to show you what I mean... https://jsfiddle.net/atg5m6ym/5230/

Expected output would be something like this:

{
    "username": "johndoe",
    "email": "[email protected]",
    ...
}

This way currently does not work... How can I make this into a js object or if someone could offer a better way of doing this, that would be great. Thank you for your help in advance!

Upvotes: 3

Views: 971

Answers (2)

tymcsilva
tymcsilva

Reputation: 146

Non-jQuery version:

var formElements = document.getElementById('form_name').childNodes;
var obj = {};
for(element in formElements) {
  if(formElements[element].nodeName === 'INPUT') {
    obj[formElements[element].id] = formElements[element].value
  }
};

https://jsfiddle.net/d5uejqLf/

Upvotes: 2

Ben
Ben

Reputation: 96

You should not return data object in the each loop, but after:

var setData = function(){
   var data = {};

   $('#form_name').filter(':input').each(function() {
       const $id = $(this).attr('id');
       const $value = $(this).attr('value');
       data[$id] = $value;
   });

   return data;
}

var data = setObject();

also, you should not define your object as a constant since you change its value right after

Upvotes: 3

Related Questions