Undo Redo

Form undo redo

by doug65536

HTML

<button id="undo" disabled>Undo</button>
<button id="redo" disabled>Redo</button>
<input type="text">
<input type="text">
<input type="text">

JavaScript

$(function () {
    "use strict";

    var undostack = [];
    var undoptr = 0;

    $.fn.enable = function () {
        return this.each(function () {
            $(this).removeAttr('disabled');
        });
    };
    $.fn.disable = function () {
        return this.each(function () {
            $(this).attr('disabled', 'true');
        });
    };

    $('#undo').on('click', function () {
        if (undoptr > 0) {
            --undoptr;
            undostack[undoptr][0].val(undostack[undoptr][1]);
            if (undoptr == 0) {
                $('#undo').disable();
            }
            $('#redo').enable();
        }
    });

    $('#redo').on('click', function () {
        if (undoptr < undostack.length) {
            undostack[undoptr][0].val(undostack[undoptr][2]);
            ++undoptr;
            if (undoptr >= undostack.length) {
                $('#redo').disable();
            }
            $('#undo').enable();
        }
    });

    $('input[type="text"]').on({
        focus: function () {
            var elem = $(this);
            elem.data('orig-value', elem.val());
        },
        blur: function () {
            var elem = $(this),
                oldval = elem.data('orig-value'),
                newval = elem.val();
            if (oldval !== newval) {
                undostack.length = undoptr;
                undostack[undoptr++] = [elem, oldval, newval];
                $('#undo').enable();
                $('#redo').disable();
            }
        }
    });

});