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


i need post form data using jquery , field input values needs posted in json format. problem form fields comprise of fields there like: first name, last name , email, fields after of number because form constructed request. 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 wont work remaining fields. ideally need each function or loop through these other questions , put loop json.stringify have no idea how that. might why don't use:

$('form').serialize(); 

to form data problem json needs in following format

{   "firstname": "string",   "lastname": "string",   "email": "string",   "responses": [     {       "questionkey": 0, //this needs id of input       "responsetext": "string", //this needs value of input     } //with part of json repeating each question   ] } 

all these additional fields have same input class can work them in jquery. stuck , appreciate help. thank :)

update - below example of 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 number of these 'unknown-questions' class inputs 

complete form serialized 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


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -