I have this code
I like Teneff's answer the best, however his implementation is flawed in that it doesn't fit the requirement that only selected inputs are reset to defaults. It is unclear as to whether the OP wanted other inputs to be cleared or not, so I created the clearNonDefaults
variable. When set to true
this will clear the value of other inputs.
// make sure Mozilla's very handy array extension is implemented
if(Array.prototype.indexOf === undefined)
{
Array.prototype.indexOf = function(val)
{
for (var i = 0; i < this.length; i++)
{
if(this[i] == val)
return i;
}
return -1;
};
}
var inputsToRestore, clearNonDefaults, defaults = [], elements = [];
// if you want to empty the values of inputs other than those listed in inputsToRestore, set to true.
clearNonDefaults = false;
// if you ever want to add more, just place the name in this array.
inputsToRestore = ['c'];
function onLoadHandler () {
elements = document.getElementsByTagName('input');
for (i=0; i -1) {
defaults[elements[i].name] = elements[i].value;
}
}
}
function resetHandler () {
for(i=0; i -1) {
elements[i].value = defaults[elements[i].name];
} else if( clearNonDefaults === true) {
elements[i].value = '';
}
}
}
window.onload = onLoadHandler;
document.getElementById('reset').onclick = resetHandler;