Using JQUERY To Create JSON From Input Values

April 21, 2017

In a recent project I needed to save a user’s response as JSON, so that I could recreate it in a PDF. I added some data attributes to the inputs, and passed the JSON to a hidden field where it would be submitted to the controller.

        $('[data-submit-response]').on('click', function(e) {
            var $response = [];
            $('[data-response-input]').each(function() {
                    'field_id': $(this).data('field-id'),
                    'field_label': $(this).data('label'),
                    'field_response': $(this).val()