Thursday, February 6, 2014

Get a JSON Object from HTML form

Found this great JS library which can be used to serialize an HTML Form to a JavaScript Object

Example HTML form
<form id="my-form">
  <input type="text" name="name"              value="david" />

  <!-- object -->
  <input type="text" name="address[city]"         value="Melbourne" />
  <input type="text" name="address[state][name]"  value="Victoria" />
  <input type="text" name="address[state][abbr]"  value="VIC" />
</form>

Java Script
var jsonData = $('#my-form').serializeJSON();

Return value
{
  name: "david",

  address: {
    city: "Melbourne",
    state: {
      name: "Victoria",
      abbr: "VIC"
    }
  }
}

Install

Download the jquery.serializeJSON.min.js(https://raw.github.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializeJSON.min.js) script and include in your page after jQuery, for example:

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.serializeJSON.min.js"></script>

Reference :https://github.com/marioizquierdo/jquery.serializeJSON

No comments:

Post a Comment