3

I am having some issues getting the data out of my HTML form and into the proper JSON format that is required by the server that I'm sending to. I've tried following along this guide I found for extracting the data and formatting as JavaScript Object, but I cannot get the output to match what I'll need to send off.

I have been able to get the question key that I need, along with it's proper value, but have been unable to add the proper labeling.

Current Output:

{"Question1":"Yes",
"Question2":"No",
"Question3":"1",
"Question4":"Female"}

Required Output:

{
"Key":"Question1",
"Value":"Yes"
 }, {
"Key":"Question2",
"Value":"No"
 }, {
"Key":"Question1",
"Value":"No"
 }, {
 "Key":"Question4",
 "Value":"Female"
 }

(I included the script for the serializeJSON plugin to get the snippet to work)

$(function(){
var $select = $(".1-100");
for (i=1;i<=100;i++){
    $select.append($('<option></option>').val(i).html(i))
 }
});	

function submitForm () { 


var result = [];
$.each($('form').serializeArray(), function(i,field){
result.push({"Key": field.name, "Value":field.value})
 
});
  
var formData = JSON.stringify($(result));	
	console.log(formData);
};
  
	
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="survey" method="post">
	<div class="form-group">
 	<div class="col-sm-3 selectContainer">
		
	 <label class="control-label" >First Question</label>
  		<select class="form-control" name="QuestionKey1">
    		<option name="Value" value="Yes" selected>Yes</option>
    		<option name="Value" value="No">No</option>
  		</select>
	</div>	
		
	<div class="col-sm-3 selectContainer">	
  		<label class="control-label">Second Question</label>
  			<select class="form-control" name="QuestionKey2">
    			<option name="Value" value="Yes">Yes</option>
    			<option name="Value" value="No" selected>No</option>
 			 </select>
		</div>
				
	<div class="col-sm-2 selectContainer">
		  <label class="control-label">Third Question</label>	
			<select class="form-control 1-100" id="age" name="QuestionKey3"></select>
    </div>
		
		<div class="col-sm-2">
		 <label class="control-label">Fourth Question</label>	
			 <label class="radio-inline">
			 	<input type="radio" name="QuestionKey4" value="Female" />Female
			  </label>
			  <label class="radio-inline">
				 <input type="radio" name="QuestionKey4" value="Male" />Male
			  </label>	
		
		</div>	
		</div>				
	<input value="Submit" type="button" onclick="submitForm()">	
</form>

Any tips or advice would be greatly appreciated. Thank you.

Edit - After following one of the examples sent I am ending up with my output looking like this:

{"0":{"Key":"QuestionKey1","Value":"Yes"},"1": 
{"Key":"QuestionKey2","Value":"No"},"2": 
{"Key":"QuestionKey3","Value":"1"},"3": 
{"Key":"QuestionKey4","Value":"Male"},"length":4}

I've also modified my snippet to reflect the changes that got me to this point.

2 Answers 2

2

Try something like this: (no need for that plugin), using http://api.jquery.com/serializeArray/

var result = [];    
$.each($('form').serializeArray(), function(i, field){
    result.push({"Key": field.name, "Value":field.value})
});

finally call JSON.stringify if you need it in string format

Sign up to request clarification or add additional context in comments.

3 Comments

This response gives me nearly what I'm looking for, I was just wondering if you knew how I would get rid of the numbering and length that comes along with the output? I didn't see it in the documentation and examples for serializeArray, perhaps I am missing a step? I edited my post to reflect the changes.
Call JSON.stringify on the plain javascript object without converting it to a jquery object. I.e. JSON.stringify(result)
This solution worked for me like a charm. Thank you very much for your help with this.
1

Firstly note that the on* event attributes are outdated. You should use unobtrusive event handlers instead. Also, when dealing with forms you should hook to the submit event of the form element, not the click of the submit button. This is for accessibility purposes.

With regard to your actual issue, you don't need to use the serializeJSON plugin. jQuery's own serializeArray() method gets you close to the data format you need, however it returns an array of objects with name and value keys, not a single object keyed by the name of the input itself. To fix that you can loop through the array, something like this:

$(function() {
  var $select = $(".1-100");
  for (i = 1; i <= 100; i++) {
    $select.append($('<option></option>').val(i).html(i))
  }

  $('#survey').on('submit', function(e) {
    e.preventDefault();
    
    var obj = {};
    $(this).serializeArray().forEach(function(arr) {
      obj[arr.name] = arr.value;
    })
    
    console.log(obj);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="survey" method="post">
  <div class="form-group">
    <div class="col-sm-3 selectContainer">
      <label class="control-label">First Question</label>
      <select class="form-control" name="QuestionKey1">
        <option name="Value" value="Yes" selected>Yes</option>
        <option name="Value" value="No">No</option>
      </select>
    </div>
    <div class="col-sm-3 selectContainer">
      <label class="control-label">Second Question</label>
      <select class="form-control" name="QuestionKey2">
        <option name="Value" value="Yes">Yes</option>
        <option name="Value" value="No" selected>No</option>
      </select>
    </div>
    <div class="col-sm-2 selectContainer">
      <label class="control-label">Third Question</label>
      <select class="form-control 1-100" id="age" name="QuestionKey3"></select>
    </div>

    <div class="col-sm-2">
      <label class="control-label">Fourth Question</label>
      <label class="radio-inline">
        <input type="radio" name="QuestionKey4" value="Female" />Female
      </label>
      <label class="radio-inline">
        <input type="radio" name="QuestionKey4" value="Male" />Male
      </label>
    </div>
  </div>
  <button type="submit">Submit</button>
</form>

1 Comment

Thanks for the info on the about the onclick events, I didn't realize they were outdated. I will modify my forms from now own to meet this standard. serializeArray() works well to format how I needed it to, and you were right about not needing that plugin. Thanks for your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.