user1190132 user1190132 - 6 months ago 10
JSON Question

Post data from form without knowing how long the form will be

I need to post some form data using jQuery and the field input values needs to be posted in a JSON format. The problem is that the form fields comprise of fields that will definitely be there like: First Name, Last Name and Email, however the fields after this could be of any number because the form is constructed from a GET request. So normally I would do something like this:

var firstName = $('input[name="firstName"]').val();
var lastName = $('input[name="lastName"]').val();
var email = $('input[name="email"]').val();

data: JSON.stringify({
"firstName": firstName,
"lastName": lastName,
"email": email
})


However this wont work for my remaining fields. So ideally I need to do like an each function or something to loop through these other questions and put this loop into the JSON.stringify but I have no idea how to do that. But then you might say why don't you just use:

$('form').serialize();


to just get all the form data but the problem is that the JSON needs to be in the following format

{
"firstName": "string",
"lastName": "string",
"email": "string",
"responses": [
{
"questionKey": 0, //this needs to be the ID of the input
"responseText": "string", //this needs to the value of the input
} //with this part of the JSON repeating for each question
]
}


All these additional fields have the same input class so I can work with them easily in jQuery. I am really stuck and I would really appreciate your help. Thank you :)

UPDATE - below is an example of the form fields:

<input name="firstName" id="firstName" type="text" class="known-questions">
<input name="lastName" id="lastName" type="text" class="known-questions">
<input name="email" id="email" type="email" class="known-questions">
<input name="45435345345" id="45435345345" type="text" class="unknown-questions">
<input name="43443539864" id="43443539864" type="text" class="unknown-questions">
<input name="43344243529" id="43344243529" type="text" class="unknown-questions"> //there could be any number of these 'unknown-questions' class inputs

Answer

Complete form serialized to required structure:

var data ={};
$('.known-questions').each(function(){
    data[this.name] = this.value;
});

data.responses = $('.unknown-questions').map(function(){
   return {questionKey: this.id, responseText:this.value};
}).get();

var postJson = JSON.stringify(data);

DEMO