Strong Like Bull
Strong Like Bull

Reputation: 11297

How do I convert a standard HTML form to JSON representation that includes all data?

I have a simple HTML form:

<form id="formid1" action="#" method="post">
    <table>
        <tr><td> First name: </td><td><input type="text" name="firstname" id="firstname"/>  </td></tr>
        <tr><td>  Last name: </td><td><input type="text" name="lastname" id="lastname"/>  </td></tr>
        <tr><td> Address:  </td><td> <input type="text" name="address" id="address"/> </td></tr>
        <tr><td> Zip: </td><td> <input type="text" name="zip" id="zip"/> </td></tr>
        <tr><td> Sex:  </td><td> <input type="radio" name="sex" value="male" /> Male<br />
            <input type="radio" name="sex" value="female" /> Female<br /></td></tr>

        <tr><td>  </td><td>  <input type="submit" value="Submit" /></td></tr>

    </table>
</form>

I need to get a JSON representation of the Form elements including id, value, type, form action, form id etc.

I tried playing with the following code but I am not getting what I am looking for:

<script>
$(document).ready(function(){

    var encoded = $.toJSON($('#formid1')); 

    $("#formid1").submit(function() {
  $.colorbox({html:'<p>Form Converted to JSON Data: <br /><br /><br /><br /><br /></p>'+ encoded  });
      return false;
    });

    });
</script>

I get:

{"length":1,"0":{"firstname":{},"lastname":{},"address":{},"zip":{},"sex":{"0":{},"1":{}},"6":{}},"context":{"jQuery16108216209608688556":1},"selector":"#formid1"}

close

Upvotes: 3

Views: 22190

Answers (2)

sh0rug0ru
sh0rug0ru

Reputation: 1626

Try this:

$('#formid1').serializeArray().reduce(function(obj, v) { obj[v.name] = v.value; return obj; }, { });

Upvotes: 1

Domenic Bove
Domenic Bove

Reputation: 506

Hi I'm working on the same problem! The way I went around it was by using an onsubmit function rather than action. You pass everything within the form to a javascript function which then gives you access to the form data. The function I made uses an alert to show you have access to that data. Here's the code:

<html>
<body>

<form onsubmit="handleForm(this)">
<table>
    <tr><td> First name: </td><td><input type="text" name="firstname"  id="firstname"/>  </td></tr>
    <tr><td>  Last name: </td><td><input type="text" name="lastname" id="lastname"/>  </td></tr>
    <tr><td> Address:  </td><td> <input type="text" name="address" id="address"/> </td></tr>
    <tr><td> Zip: </td><td> <input type="text" name="zip" id="zip"/> </td></tr>
    <tr><td> Sex:  </td><td> <input type="radio" name="sex" value="male" /> Male<br />
        <input type="radio" name="sex" value="female" /> Female<br /></td></tr>

    <tr><td>  </td><td>  <input type="submit" value="Submit" /></td></tr>

</table>
</form>

<script>
function handleForm(arr) {
    alert(arr['firstname'].value + arr['lastname'].value);
}
</script>

</body>
</html>

Upvotes: 0

Related Questions