Search code examples
javascriptformsinputfieldonfocus

clear form fields onblur on all fields


Hey so I am working on a calculator with a form and javascript. I want that when the user clicks in a field and the value is "0" the field gets cleared. When he clicks outside the field while the value is "" I want the field to be filled again with 0. I can easily do so for specific fields like that:

document.forms[0].elements[0].onfocus = function() {
    if(this.value == "0") {
        this.value = "";
    }
};

document.forms[0].elements[0].onblur = function() {
    if(this.value == "") {
        this.value = "0";
    }
};

But I want it to work with every field and I don't want to write this bunch of code for every field and I do not want to use inline references in my html. Which option do I have? Thanks in advance.


Solution

  • Try this.

    You can also replace the 'document.forms[0].elements' by 'document.querySelectorAll("form input")', etc.

    Array.prototype.slice.call(document.forms[0].elements).forEach(function(element){
        element.onfocus = function() {
            if(this.value == "0") {
                this.value = "";
            }
        };
        element.onblur = function() {
            if(this.value == "") {
                this.value = "0";
            }
        };
    })