JSFiddle - React, Tailwind, and code Playground

by Laurens Maneschijn

HTML

fork from: <a target="_blank" href="http://jsfiddle.net/8fpLx/10/">jsfiddle.net/8fpLx/10/</a> , 
linked from here: <a target="_blank" href="https://stackoverflow.com/a/18267327/1158769">SO</a>


<form class="foo">
	<input name="address[permanent][name]" type="text" value="My Address"><br>
	<input name="address[permanent][street][street_one]" type="text" value="My Street One"><br>
	<input name="address[permanent][street][street_two]" type="text" value="My Street Two"><br>
	<input name="cb1" type="checkbox" value="cb1_1" checked>
	<input name="cb1" type="checkbox" value="cb1_2" checked> (overwrites previous, as expected)
	<br>
	<input name="cb2[a]" type="checkbox" value="cb2_1" checked>
	<input name="cb2[a]" type="checkbox" value="cb2_2" checked>
	<br>
	<!-- WARNING something in here seems to crash the page, see JS:
	<input name="cb3[]" type="checkbox" value="cb3_1" checked>
	<input name="cb3[]" type="checkbox" value="cb3_2" checked>
	<br>
	-->
	<select multiple name="selects[x]">
		<option>1</option>
		<option selected>2</option>
		<option selected>3</option>
	</select>
</form>

<button onclick="run();">run</button>

<pre id="result"></pre>

This works for the original address examples, but when I try other names it is no good.<br>
I get a weird "cb" property, even though there is no name="cb".<br>
Also when I use name="myname[]" with empty [] it just crashes the page.

CSS

pre#result {
	tab-size: 2;
}

JavaScript

$(document).ready(function(){
//	run();
});

function run() {
        var form = {};
        $(':input', $('.foo')).each(function(){
          var top = form;
          var path = $(this).attr('name');
          var val = $(this).val();
          var prev = '';
		  var count = 0;
		  // WARNING: it seems to crash on a path with empty [] like name="myname[]" :
		  // the count failsafe break does not help... it seems to crash within the path.replace() function...
          while ((path.replace(/^(\[?\w+\]?)(.*)$/, function(_m, _part, _rest) {
		  	if(++count > 1000) {
				console.log('failsafe runaway loop on element:', path, val, this);
				throw new Error('failsafe runaway loop');
				//return false;
			}
            prev = path;
            _part = _part.replace(/[^A-Za-z_]/g, '');
            if (!top[_part]) {
              if (/\w+/.test(_rest)) { 
                top[_part] = {}; 
                top = top[_part];
              } else {
                top[_part] = val; 
              }
            } else if (!/\w+/.test(_rest)) {
              top[_part] = val;
            } else {
              top = top[_part];
            }
            path = _rest;
          })) && (prev !== path));
        });
	console.log(form);
	console.log(JSON.stringify(form, null, '\t'));
	document.querySelector('#result').innerText = JSON.stringify(form, null, '\t');
//  alert("form.address.permanent.street.street_two: "+form.address.permanent.street.street_two);
};