Search code examples
javascriptinputtextwindowonfocus

How to Change the Value of an Input Field Back off Focus


I have managed to change the text value of the input field onfocus to nothing, but I can't work out how to get it to change back on the onclick of anywhere else on the webpage HTML:

<input type="text" value="this is value" id="text">

JS:

 document.getElementById("text").onfocus = function() {
            var value = "on"
            if (value==="on") {
            document.getElementById("text").value=""
                value="off"
            } else {
                document.getElementById("text").value="this is value"
                value="on"
            }
            window.onclick = function() {
                document.getElementById("text").value="this is value"
            }
        }

Solution

  • I'm not sure if I got you right. But I don't think you need this much-complicated stuff here, you can just simply use placeholder. Then you can clear it on the input focus with onfocus event and again show it with onblur event if you like.

    <input type="text" placeholder="this is value" onfocus="this.placeholder = ''" onblur="this.placeholder = 'this is value'" id="text">

    Otherwise, you can simply create the placeholder and leave it be till the user fill the input with their desired value.

    <input type="text" placeholder="this is value" id="text">