user13398128
user13398128

Reputation:

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"
            }
        }

Upvotes: 2

Views: 6878

Answers (3)

MaximilianK
MaximilianK

Reputation: 63

Next to the onfocus event there is the onblur event. The second one will be called, when something else was liked and the input losses the focus. Checkout this article.

The following code should fulfill your requirement:

 document.getElementById("text").onfocus = function() {
    document.getElementById("text").value=""
 }
document.getElementById("text").onblur = function() {
    document.getElementById("text").value="this is value"
}

Upvotes: 0

SMAKSS
SMAKSS

Reputation: 10520

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">

Upvotes: 1

Jaroslav Zavodny
Jaroslav Zavodny

Reputation: 13

I don't exactly know what are you trying, but I think you maybe need a blur event.

var input = document.getElementById("text");
var value = "on";

input.addEventListener("focus", function() {
  if (value == "on") {
    input.value = "";
    value = "off";
  }
  else {
    text.value = "this is value";
    value = "on";
  }
});

input.addEventListener("blur", function () {
  input.value = "this is value";
  value = "on";
});
<input type="text" value="this is value" id="text">

Upvotes: 0

Related Questions