Simple Javascript to clear input boxes and automatically refill them using focus and blur event listeners

The following code automatically clears form input boxes when they are clicked on. If still empty, they are reset to the original values when they lose focus again. This will not work for textarea tags. This will only work if the id attribute of the input tag is not set or is not being used by anything else like the stylesheet. In this code, the id attribute is used to store an index into an array (results) that contains the original input tag values. This array is referenced whenever a blur or focus event occurs on that input box. There are many, many ways to do this that are more efficient. However, this can just be dropped onto a page at the bottom if the conditions stated above are met. Make sure to add the code after the form is defined in the html.

<script type=”text/javascript”>
//refill forms automagically
//create new array to store original input values var results = new Array();
 //get amount of input tags var inputlength = document.getElementsByTagName(“input”).length;
 //event listener for blur function blur(e){
 //if value is empty if(””){
 //reset to orginal value[];
 //original value is stored in id attribute }
 //event listener for focus function focus(e){
 //if value is the original value if([]){
 //clear it””;
 //add event listeners to the inputs function addevents(){
 //get all input tags var els=document.getElementsByTagName(“input”);
 //loop through all of them for(var i = 0;i<els.length;i++){
 //store the original values in results results[i]=els[i].value;
var el =els[i];
  //add event listeners to the input el.addEventListener(‘blur’,blur,false);
  //add event listeners to the input el.addEventListener(‘focus’,focus,false);
//if its not a submit button, set the id attribute to the index. if(el.type!=”submit”){;}



Comments are closed.