Friday, 17 June 2016

jQuery get all the input tags and convert them into json object.

Simple example to get all the input values from the form and convert them into the json object.

HTML:
<form id="form_data">
    <div>
        <lable>Name</lable>
        <input type="text" id="Name" value="test" />
    </div>
    <div>
        <lable>Email</lable>
        <input type="text" id="Email" value="test@gmail.com" />
    </div>
    <div>
        <lable>Name</lable>
        <input type="text" id="Password" value="123123"/>
    </div>
</form>


Put it as a function into your js file where you want to consume this:


function getFormData($form){
   var unindexed_array = $form.serializeArray();
   var indexed_array = {};
   $.map(unindexed_array, function(n, i){
       indexed_array[n['name']] = n['value'];
   });
   return indexed_array;
}

Usage:
var $form = $("#form_data");
var data = getFormData($form);

This function will return all the controls values in json form like:
{
Name:"test",
Email:"test@gmail.com",
Pasword:"123123"

}


No comments:

Post a Comment