Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="wrapper">

  <div id="panel" class="panel panel-warning">
  <div class="panel-heading">
    <h3 class="panel-title">Jsonify Options <a href="https://blog.sverrirs.com/2017/03/jsonify-inputfield-values-before-submit.html" target="_blank">(blog.sverrirs.com)</a></h3>
  </div>
  <div class="panel-body" id="jsonifyoptions">
    <div class="col-lg-3 col-md-6">
      <div class="form-group">
        <label class="control-label">Only serialize fields under parent</label>
        <span class="help-block">By specifying a parent element only serialization fields under that element are parsed.</span>
        <div class="radio radio-primary">
          <label><input type="radio" name="rbSerializeElement" id="rbSerializeElement1" value="body" checked="" serialize-as="jsonify.parent">document.body (all)</label>
        </div>
        <div class="radio radio-primary">
          <label><input type="radio" name="rbSerializeElement" id="rbSerializeElement2" value="#fb" serialize-as="jsonify.parent">Facebook</label>
        </div>
        <div class="radio radio-primary">
          <label><input type="radio" name="rbSerializeElement" id="rbSerializeElement3" value="#twitter" serialize-as="jsonify.parent">Twitter</label>
        </div>
        <div class="radio radio-primary">
          <label><input type="radio" name="rbSerializeElement" id="rbSerializeElement4" value="#jsonifyoptions" serialize-as="jsonify.parent">Jsonify Options</label>
        </div>
      </div>
    </div>
    
    <div class="col-lg-3 col-md-6">
      <div class="form-group">
        <label class="control-label">Empty string handling</label>
        <span class="help-block">Should empty values be returned as "" or null values?</span>
        <div class="radio radio-primary">
          <label><input type="radio" name="rbSerializeNull" id="rbSerializeNull1" value="true" checked="" serialize-as="jsonify.usenull">Use Null</label>
        </div>
        <div class="radio radio-primary">
          <label><input type="radio" name="rbSerializeNull" id="rbSerializeNull2" value="false" serialize-as="jsonify.usenull">Empty string</label>
        </div>
      </div>
    </div>
    
    <div class="clearfix visible-md-block visible-sm-block"></div>
    
    <div class="col-lg-3 col-md-6">
      <div class="form-group">
        <label class="control-label">Parse numbers?</label>
        <span class="help-block">Should numerical values be parsed or left as strings? Note: numbers starting with zero will never be parsed as number.</span>
        <div class="radio radio-primary">
          <label><input type="radio" name="rbSerializeNumber" id="rbSerializeNumber1" value="true" checked="" serialize-as="jsonify.usenumbers">Use numbers</label>
        </div>
        <div class="radio radio-primary">
          <label><input type="radio" name="rbSerializeNumber" id="rbSerializeNumber1" value="false" serialize-as="jsonify.usenumbers">Use strings</label>
        </div>
      </div>
    </div>
    
    <div class="col-lg-3 col-md-6">
      <div class="form-group">
        <label class="control-label">Use alternative serialization attribute</label>
        <span class="help-block">You can instruct the code to read from different serialization attributes on your elements. By doing this you can obtain a completely different json result.</span>
        <div class="radio radio-primary">
          <label><input type="radio" name="rbSerializationAttr" id="rbSerializationAttr1" value="serialize-as" checked="" serialize-as="jsonify.attribute" serialize-alt="js.attribute">Use <code>serialize-as</code></label>
        </div>
        <div class="radio radio-primary">
          <label><input type="radio" name="rbSerializationAttr" id="rbSerializationAttr2" value="serialize-alt" serialize-as="jsonify.attribute" serialize-alt="js.attribute">Use <code>serialize-alt</code></label>
        </div>
      </div>
    </div>
    
    <div class="clearfix"></div>
    
    <div class="col-lg-12" id="jscode">
      
    </div>
  </div>
</div>

  <div id="settings" class="col-md-6 col-sm-12">
  <form action="">
    <div class="col-lg-6 col-md-12">
    <div id="general">
      <h2>Edit all of this stuff</h2>
      <div id="general_settings">
        <div class="form-group" ref="reqBlogger">
          <input type="text" class="form-control floating-label" id="txtSiteName" serialize-as="site_name" serialize-alt="site.name" placeholder="Site Name" value="My awesome site" />
          <span class="help-block">The values update as you type.</span>
        </div>
        
        <div id="selWebsiteTypeCont" class="form-group" ref="reqBlogger">
          <select class="form-control floating-label" id="selWebsiteType" placeholder="Your Website Type" serialize-as="general.website_type" serialize-alt="site.type">
            <option value="static">Static HTML</option>
            <option value="php">PHP</option>
            <option value="asp.net">ASP.NET</option>
            <option value="blogger">Blogger.com</option>
          </select>
          <span class="help-block">Select boxes are supported as well</span>
        </div>
        
        <div class="form-group" ref="reqBlogger">
          <label class="control-label" for="txtYourName">Keywords</label>
          <input type="text" class="form-control" id="txtKeywords" serialize-as="general.keywords"  serialize-alt="seo.keywords" serialize-separator="," value="software, services, seo">
          <span class="help-block">Use the <b>serialize-separator</b> attribute to automatically convert the text to an array of items. In this case it is set to split on <b>comma</b> (,).</span>
        </div>
        
        <div class="form-group">
            <label for="txtDescription" class="control-label">Description</label>
            <textarea class="form-control" rows="2" id="txtDescription" serialize-as="general.description" serialize-alt="seo.desc">Multi 
lines, 
cool!</textarea>
          <span class="help-block">Multi line textareas work as well and produce a <b>\n</b> new line character for line breaks.</span>
        </div>
        
        <div class="form-group">
          <label class="control-label">Page type</label>
          <div class="radio radio-primary">
            <label>
              <input type="radio" name="rbPageType" id="rbPageType1" value="article" checked="" serialize-as="general.page_type" serialize-alt="seo.type" />
              Article
            </label>
          </div>
          <div class="radio radio-primary">
            <label>
              <input type="radio" name="rbPageType" id="rbPageType2" value="blog" serialize-as="general.page_type" serialize-alt="seo.type" />
              Blog
            </label>
          </div>
          <span class="help-block">Radio button groups use the value assigned to each radiobutton.</span>
        </div>
        
       <div class="form-group" ref="reqBlogger">
          <label class="control-label" for="txtLocale">Net Worth</label>
          <input type="text" class="form-control" id="txtLocale" value="100546" serialize-as="networth" serialize-alt="site.income">
         <span class="help-block">This field value will be parsed as number if the <b>parsenumbers</b> option is enabled.</span>
        </div>        
      </div>
    </div>
</div>
    <div class="col-lg-6">
    <div id="fb">
      <h2>
      <div class="inline togglebutton togglebutton-material-indigo">
        <label>
          <input id="fb_enabled" type="checkbox" serialize-as="facebook.enabled" serialize-alt="services.facebook" checked="">
        </label>
      </div> Facebook</h2>
      <div id="fb_settings">
        <div class="form-group" ref="reqBlogger">
          <label class="control-label" for="txtFbUsername">Facebook Username</label>
          <input type="text" class="form-control" id="txtFbUsername" serialize-as="facebook.username" value="sverris">
          <span class="help-block">Checkboxes are interpreted as boolean by default (true if checked, false otherwise). If they have a value attribute then that value is used.</span>
        </div>
      </div>
    </div>

    <div id="twitter">
      <h2>
      <div class="inline togglebutton togglebutton-material-cyan">
        <label>
          <input id="twitter_enabled" type="checkbox" serialize-as="twitter.enabled" serialize-alt="services.twitter">
        </label>
      </div> Twitter</h2>
        <div id="twitter_settings">
          <div class="form-group" ref="reqBlogger">
            <label class="control-label" for="txtTwitterUsername">Twitter Username</label>
            <input type="text" class="form-control" id="txtTwitterUsername" serialize-as="twitter.username">
          </div>
          
          <div class="form-group">
            <label class="control-label">Card Type</label>
            <div class="radio radio-primary">
              <label>
                <input type="radio" name="rbTwitterCardType" id="rbTwitterCardType1" value="summary_large_image" checked="" serialize-as="twitter.cardtype">
                Summary Card w/large image
              </label>
            </div>
            <div class="radio radio-primary">
              <label>
                <input type="radio" name="rbTwitterCardType" id="rbTwitterCardType2" value="summary" serialize-as="twitter.cardtype">
                Summary Card
              </label>
            </div>
          </div>
        </div>
    </div>

    <div id="gplus">
      <h2>
      <div class="inline togglebutton togglebutton-material-red">
        <label>
          <input id="gplus_enabled" type="checkbox" serialize-as="gplus.enabled" serialize-alt="services.google">
        </label>
      </div> Google+</h2>
      <div id="gplus_settings">
        <div class="form-group" ref="reqBlogger">
          <label class="control-label" for="txtGplusProfileUrl">Profile URL</label>
          <input type="text" class="form-control" id="txtGplusProfileUrl" serialize-as="gplus.profile_url">
          <span class="help-block">Try also playing around with the <b>jsonify options</b> above!</span>
        </div>
      </div>
    </div>
      </form>
    </div>
  </div>
  
  <!-- Now float the tag code to the right -->
  <div class="tagcode col-md-offset-1 col-md-5 col-sm-12" id="code_section_01">
  </div>
</div>
              
            
!

CSS

              
                /*
  All of this CSS is only used for the example and is not related to the jsonify code being shown.
  this form is actually from another one of my projects.
  -- Please disregard all of this CSS. -- 
*/

@import "compass/reset";
@import "compass";
@import "compass/css3";

// Reset for common elements to avoid issues cross-browser
html, body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, 
pre, form, fieldset, input, textarea, p, blockquote, th, td { 
  padding:0;
  margin:0;
}


/* Spacing */
$settings_width: 650px;

/* colours */
$h2_color: 		#506982;

*{
	@include box-sizing(border-box);
}

/* 
Fancy body background, from: https://codepen.io/babbardel/pen/BNgZwM/ 
*/
$body_bg_fill_color: #bbcdcc;
$body_bg_pattern_color: #fff;
$body_bg_pattern_dot_color: #fff;
$body_bg_pattern_star_color: #fff;
$body_bg_pattern_circle_color: #fff;

body {
  background-color:$body_bg_fill_color;
  @include background-image(
    radial-gradient($body_bg_pattern_dot_color 9px, transparent 10px), 
    repeating-radial-gradient($body_bg_pattern_star_color 0, $body_bg_pattern_star_color 4px, transparent 5px, transparent 20px, $body_bg_pattern_circle_color 21px, $body_bg_pattern_circle_color 25px, transparent 26px, transparent 50px)
  );    
  @include background-size(30px 30px, 90px 90px); 
  background-position: 0 0;
}

body{
	font-family: 'Lato', 'sans-serif';
	font-weight: 400;
  margin-top: 3em;
}
a{
  text-decoration: none;
}

// Spacing for panel
#panel{
  margin: 20px auto;
  min-width: 300px;
}

/* Two column layout and content spacing */
#wrapper
{ 
  //display: table;
  margin: 20px auto;
  width: 80%;
  //min-width: 1000px;
  min-height: 400px;
}

#settings
{
  padding:0.2em;
  padding-top: 1.5em;
  margin-bottom: 2em;
  background: #f5f5f5;
  vertical-align: top;
  min-width: 300px;
  @include border-radius(5px);
  @include box-shadow(0 20px 20px rgba(0,0,0,.3));
}

#jscode{
  pre
  {
    text-align:center;
    overflow: auto;
    font-size: 16px;
    background: #4a4a4a;
    padding:10px; 
    @include box-shadow(0 20px 20px rgba(0,0,0,.3));
  }
}
.tagcode
{
  vertical-align: top;
  padding-left:0;
  height:100%;
  pre
  {
    overflow: hidden;
    font-size: 16px;
    background: #4a4a4a;
    padding-left:10px; 
    padding-top:10px; 
    height: 100%;
    min-width: 300px;
    @include box-shadow(0 20px 20px rgba(0,0,0,.3));
  }
}

/* Individual page element styles */
h2{
	font-size: 22px;
	text-transform: uppercase;
	font-weight: 300;
	text-align: left;
	color: $h2_color;
	border-bottom: 1px solid $h2_color;
	padding-bottom: 3px;
	margin-bottom: 20px;
}

.inline
{
  display: inline-block;
  vertical-align: middle;
  padding-bottom: 10px;
}

/* Overrides for material controls */
.control-label
{
  font-weight: bold;
  font-size: 14px;
}

.checkbox span.checkbox-material
{
  margin-right: 5px;
}

.help-block
{
  font-size: 12px;
  color: #b3b3b3;
  
  b {
    font-weight:bold;
    color: black;
  }
}

.form-group .floating-label
{
  font-weight: bold;
  color: black;
}

/* Customizing the icons behind select inputs */
#selWebsiteTypeCont .dropdownjs:after
{
  //content: "\e629";
  content: " ";
  right: 3px;
  top: 0px
}

// Initially hide all the settins sections
#fb_settings, #twitter_settings, #gplus_settings, #pinterest_settings, #other_settings, #general_settings
{
  padding-left: 10px;
  padding-bottom: 30px;
}

#general_settings
{
  display: block;
}
              
            
!

JS

              
                /*
THIS IS THE MAIN and ONLY FUNCTION, simply copy this to your project.
See: https://blog.sverrirs.com/2017/03/jsonify-inputfield-values-before-submit.html
*/
function jsonify(parentEl, attributeName, separatorName, options = {'usenull':true, 'parsenumbers':true}) {
  // Initialize the parameters to their defaults if they're not set
  parentEl = typeof(parentEl) === typeof undefined || parentEl === null ? document.body : parentEl;
  attributeName = typeof(attributeName) === typeof undefined || attributeName === null ? "serialize-as" : attributeName;
  separatorName = typeof(separatorName) === typeof undefined || separatorName === null ? "serialize-separator" : separatorName;

  // Start the parsing
  var json = {};
  $(parentEl).find('[' + attributeName + ']').each(function() {
    // 1. Extract the data from all form controls found under the parent
    //    only consider controls that have the correct serialization attribute set
    var val = null;
    if ($(this).is(':checkbox') || $(this).is(':radio')) {
      // Special handling for checkboxes and radio buttons
      // If the control has a value attribute and is not checked then exit, 
      // as we don't want to override other values else just assign it
      var tmpValueAttr = $(this).attr('value');
      if (typeof tmpValueAttr !== typeof undefined && tmpValueAttr !== false) {
        if (!$(this).is(':checked'))
          return;
        val = $(this).val();
      } else {
        val = $(this).is(':checked');
      }
    } else {
      // All other form controls go through here
      val = $(this).val(); 
      
      // Check to see if the control has the attribute for serialization separator
      // is set, if so then split value into array on the separator
      var tmpSepAttrVal = $(this).attr(separatorName);
      if( tmpSepAttrVal && val )
        val = val.split(tmpSepAttrVal);
    }
    
    // Should we omit empty string values and use null
    if( options && options['usenull'] && (typeof val === typeof undefined || val === "" ) ){
      val = null;
    }
    // Should numerical values be parsed
    if( options && options['parsenumbers'] && val && !Array.isArray(val) && typeof(val) !== "boolean" && isFinite(val) && !isNaN(parseFloat(val)) ) {
      if( val.length > 0 && val[0] != "0" )
        val = !isNaN(parseFloat(val)) ? parseFloat(val) : parseInt(val);
    }

    // 2. Now assign it the correct place in the resulting json, if
    //    the serialization attibute is nested (has dots) then create the 
    //    necessary nested structure in the json
    var path = $(this).attr(attributeName).split('.');
    var path_len = path.length; data = null;
    $.each(path, function(index, key) {
      if (data == null)
        data = json;
      if (index + 1 === path_len) {
        // Note: if there are duplicate keys, e.g. form elements 
        // with the same serialize attribute value then duplicates
        // then only last value will be returned.
        data[key] = val;
      } else {
        if (!(key in data))
          data[key] = {};
        data = data[key]
      }
    });
  });
  return json;
}

/************************************************************************************
Everything below this line is just used for the example project to show functionality
*************************************************************************************/

g_subelement = $("body")
g_usenull = true;
g_parsenum = true;
g_serializefield = "serialize-as"

// The doc-on-ready function to initialize stuff
$(function() {

  // When editing any of the input elements then update the JSON
  $('input,select,textarea').on('input', function() {
    refreshView();
  });

  // When editing any of the input elements then update the JSON
  $('input,select,textarea').change(function() {
    refreshView();
  });
  
  // Settings for the Jsonify function
  $('#rbSerializeElement1, #rbSerializeElement2, #rbSerializeElement3, #rbSerializeElement4').change(function(){
    if( $(this).is(':checked') ){
      g_subelement = $($(this).val());
      refreshView();
    }
  });
  
  $('#rbSerializeNull1, #rbSerializeNull2').change(function(){
    if( $(this).is(':checked') ){
      g_usenull = $(this).val() === "true";
      refreshView();
    }
  });
  
  $('#rbSerializeNumber1, #rbSerializeNumber2').change(function(){
    if( $(this).is(':checked') ){
      g_parsenum = $(this).val() === "true";
      refreshView();
    }
  });
  
  $('#rbSerializationAttr1, #rbSerializationAttr2').change(function(){
    if( $(this).is(':checked') ){
      g_serializefield = $(this).val();
      refreshView();
    }
  });

  // Do an initial run so that we have some JSON to show
  refreshView();
});

function refreshView()
{
  var jsondata = jsonify(g_subelement, g_serializefield, null, {'usenull':g_usenull, 'parsenumbers':g_parsenum});
  var ppJsonData = window.prettyPrintOne(JSON.stringify(jsondata, null, 4));
  $('#code_section_01').html('<pre>' + ppJsonData + '</pre>');
  
  var ppCode = window.prettyPrintOne("jsonify('"+g_subelement.selector+"', '"+g_serializefield+"', null, {'usenull':"+g_usenull+", 'parsenumbers':"+g_parsenum+"});", "javascript");
  $('#jscode').html('<pre>' + ppCode + '</pre>');
}
              
            
!
999px

Console