Sharing Our Passion for Technology
& continuous learning
〈  Back to Blog

Javascript functions for creating a read-only view

I’m sure you’ve all been there before. After months of creating page after page of crud screens, you’re now asked to create a read-only view of everything. I usually see this implemented with setting the readOnly attribute on every field to a variable that indicates whether or not the screen is editable. While this works, I don’t like it for three reasons:

  • I would not be confident that the readOnly value will be correctly added to every field that is later added to the application.
  • I would not trust the person originally implementing this change to modify every input the first time around. Chances are a couple will be missed.
  • I would hate to have this task assigned to me and I would hate even more giving it to someone else. "Here, go add this flag to every input on these forty screens..."

Below is my latest attempt at a general solution to this problem. Caveat Emptor - I’ve never deployed this code to a production app and I fully expect to be bit by some huge limitation when/if I ever do. Consider it food for thought…

function executeOnInputs(element, fn) {
	var inputs = element.getElementsByTagName("input");
	Array.forEach(inputs, fn);
	var textareas = element.getElementsByTagName("textarea");
	Array.forEach(textareas, fn);
}

function setReadOnly(containingDiv) {
	var fn = function(item) {
		if(item.originalValue === undefined) {
			item.originalValue = item.readOnly;
		}
		item.readOnly = true;
	};
	executeOnInputs(containingDiv, fn);
};

function restoreReadOnly(item) {
	var fn = function(item) {
		if(!(item.originalValue === undefined)) {
			item.readOnly = item.originalValue;
		}
	};
	executeOnInputs(containingDiv, fn);
}
〈  Back to Blog