JSFiddle - React, Tailwind, and code Playground

by konijn_gmail_com

HTML

<form>
    Name1
    <input id="name1" type="text">Name2
    <textarea id="name2"></textarea>Valid
    <input id="valid" type="checkbox">Go live
    <input id="golive" type="date">Time
    <input id="time" type="time">Mood
    <input id="mood" type="color">Email
    <input id="email" type="email">
    <!-- File <input id="file" type="file"> Testing this makes no sense -->
    Select
    <select id="select">
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
        <option value="value3">Value 3</option>
    </select>
    <button id="button">dumpJSON()</button>
</form>

CSS

input {
    display: block
}
textarea {
    display: block
}

JavaScript

//Simulate a JSON value coming in
var initialValues = '{"name1":"Tom J Demuyt","name2":"1\\n2\\n3","valid":false,"golive":"2015-04-20","time":"20:04","select":"value2","email":"[email protected]","a":"b","mood":"#000000"}',
      data = wireForm(initialValues);
      data.a('c');




      
      //Take a JSON string, parse it, wire it to the DOM
      //Prerequisite:  The JS  supplied `Object` is not enhanced
      function wireForm(json) {
        var o = {},
          data = JSON.parse(json),
          key;
        //There is a circle in Hell for whoever decided that checkboxes use `checked` 
        function determineValueKey(e) {
          return e.type == 'checkbox' ? 'checked' : 'value';
        }

        function createHiddenElement(key) {
          var e = document.createElement('input');
          return e.type = 'hidden', e.id = key, (document.forms[0] || document.body).appendChild(e);
        }
        o.JSON = function() {
          return JSON.stringify(data);
        };
        for(key in data) {
          //Wire each key if we can find the element          
          var e = document.getElementById(key) || createHiddenElement(key),
              valueKey = determineValueKey(e);
          o[key] = function(newValue) {
            //Did we intend to set or get?
            if(!arguments.length) {
              return data[key];
            }
            return e[valueKey] = data[key] = newValue;
          };
          o[key](data[key]);
          e.addEventListener("change", function() {
            o[key](e[valueKey]);
          }, false);
        }
        return o;
      }

      button.onclick = function(e) {
        console.log(data.JSON());
        return false;
      };