JSFiddle - React, Tailwind, and code Playground

by awolf2904

HTML

<form>
    <label for="first">check1</label>
    <input name="first" id="first" type="checkbox" />
    <label for="second">check2</label>
    <input name="second" id="second" type="checkbox" />
    <label for="third">check3</label>
    <input name="third" id="third" type="checkbox" />
    <label for="fourth">check4</label>
    <input name="fourth" id="fourth" type="checkbox" />
    <input type="submit" value="update" />
</form>

JavaScript

var data = "";

dataOrg = {
    first: 'on',
    second: 'on',
    fourth: 'on'
};
// apply org. value --> org would be from server later with an ajax request
// not added this request here to keep the code smaller.
var $checkboxes = $('form input:checkbox');
$checkboxes.map(function() {
    this.checked = dataOrg[this.id];
});
//console.log($checkboxes);

//console.log($checkboxes['first']);
// parseParams from http://stackoverflow.com/questions/1131630/the-param-inverse-function-in-javascript-jquery
function parseParams(str) {
    return str.split('&').reduce(function (params, param) {
        var paramSplit = param.split('=').map(function (value) {
            return decodeURIComponent(value.replace('+', ' '));
        });
        params[paramSplit[0]] = paramSplit[1];
        return params;
    }, {});
}

$('form').submit(function (evt) {
    evt.preventDefault();
    //console.log($(this).serialize());
    var formData = $(this).serialize();

    // source from this SO question http://stackoverflow.com/questions/10147149/how-can-i-override-jquerys-serialize-to-include-unchecked-checkboxes
    // include unchecked checkboxes. use filter to only include unchecked boxes.
    /*$.each($('form input[type=checkbox]')
        .filter(function (idx) {
        return $(this).prop('checked') === false
    }),

    function (idx, el) {
        // attach matched element names to the formData with a chosen value.
        var emptyVal = "off";
        formData += '&' + $(el).attr('name') + '=' + emptyVal;
    });*/
    
    //console.log(formData, jQuery.param(dataOrg));
    if ( jQuery.param(dataOrg) != formData ) { // check if user changed the data.
        console.info('data changed! Send update to server');
        $.ajax({
            url: '/echo/json/',
            type: 'POST',
            //data: formData, // this will work but for jsfiddle echo the code below is required.
            data: {
                json: JSON.stringify({
                    serialized:...