0

What is the best way to parse through each input on a form to produce the Json object below? I am not married to the custom Attributes, if the is a better simpler way please share it.

   <form>   
    <label>Address</label>

       <input type="text" name="address" data-label="Address" data-group="partcipantInfo" data-column="dataBaseAddress" data-internalUse="1" data-userDefined="0" value="123 Acme Way"/>


     <label>City</label>

          <input type="text" name="City" data-label="City" data-group="partcipantInfo" data-column="dataBaseCity" data-internalUse="1" data-userDefined="1" value="Loony Tunes"/>

   <input type="submit"value="Submit" />
</form>

Trying to get this result for each

{
   "inputs":[
      {
         "DataLabel":"Address",
         "DataGroup":"Address on Record",
         "DataColumn":"DataBaseAddress",
         "Value":"123 Acme Way",
         "InternalUse":true,
         "userDefined":false
      },
      {
         "DataLabel":null,
         "DataGroup":"Address on Record",
         "DataColumn":"dataBaseCity",
         "Value":"Loony Tunes",
         "InternalUse":true,
         "userDefined":true
      }
   ]
}

2 Answers 2

1

Use the jQuery serializeArray() method:

var jsonData = $("form").serializeArray();

For more info:

http://api.jquery.com/serializeArray/
Sign up to request clarification or add additional context in comments.

Comments

0

Fairly simple:

var inputs = document.querySelectorAll('input[type="text"]');
var obj = {
  inputs : Array.prototype.map.call(inputs, function(input){
    return {
      DataLabel : input.getAttribute('data-label'),
      DataGroup : input.getAttribute('data-group'),
      DataColumn : input.getAttribute('data-column'),
      Value: input.value,
      InternalUse: !!+input.getAttribute('data-internalUse'),
      userDefined: !!+input.getAttribute('data-userDefined')
    }
  })
}

console.log(obj);

DEMO: http://jsbin.com/casazame/1/edit

Note: !!+ is a short way of converting '0'/'1' to false/true.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.