Wednesday, June 24, 2009

Javascript: Clear Form Elements

function ClearValue() {

var myContainer = document.getElementById("myFormElement");

var options = myContainer.getElementsByTagName('input');

for (i = 0; i < options.length; i++) {

var opt = options[i];

if (opt.type == 'text') {

opt.value = "";

}

else if (opt.type == 'checkbox' opt.type == 'radio') {

if (opt.checked) {

opt.checked = false;

}

}

}

var options = myContainer.getElementsByTagName('textarea');

for (i = 0; i < options.length; i++) {

var opt = options[i];

opt.value = "";

}

var options = myContainer.getElementsByTagName('select');

for (i = 0; i < options.length; i++) {

var opt = options[i];

opt.selectedIndex = -1;

}

}

Reference:
Using JavaScript to reset or clear a form