admin管理员组

文章数量:1333617

I have a text input, and I want to hide the text inside, on a given event(I disable the input, when it is not needed). I would like to display the hidden text, when the given event is reversed.

I know I can store the value and retrieve as needed. I'd like to avoid moving data, since this is a purely cosmetic operation.

Can the input text be hidden, or is manipulating the data in the input the only way? I would like the simplest solution.y?

I can use pure JS and jQuery.

I have a text input, and I want to hide the text inside, on a given event(I disable the input, when it is not needed). I would like to display the hidden text, when the given event is reversed.

I know I can store the value and retrieve as needed. I'd like to avoid moving data, since this is a purely cosmetic operation.

Can the input text be hidden, or is manipulating the data in the input the only way? I would like the simplest solution.y?

I can use pure JS and jQuery.

Share Improve this question edited Dec 16, 2014 at 17:31 nobrandheroes asked Dec 15, 2014 at 18:29 nobrandheroesnobrandheroes 7581 gold badge10 silver badges18 bronze badges 2
  • 2 You can store the value in a data attribute or even in the HTMLElement object itself – Eyal Commented Dec 15, 2014 at 18:30
  • There are several ways, and selecting “better” or “simpler” are subjective, especially when no criteria have been set. Moreover, the choice might also depend on the overall program logic, which was not disclosed. – Jukka K. Korpela Commented Dec 15, 2014 at 19:23
Add a ment  | 

2 Answers 2

Reset to default 2

I would use "value" attribute of the same input object, since the attribute is the default value. In this case you don't even need any additional variables. The idea of this approach es from the difference between properties and attributes. It means that if you change value property of the object, the attribute value remains the same as it was before.

var input = document.querySelector('input');

function hide() {
    input.value = "";
}

function show() {
    input.value = input.getAttribute('value');
}
<input type="text" value="Some text">
<button onclick="hide()">Hide</button>
<button onclick="show()">Show</button>

An example on how to store the value of an input element inside the dataset of the element.

and show/hide it on hover.

var hello = document.getElementById('hello');
hello.dataset.value = hello.value;
hello.value = '';
hello.addEventListener('mouseover', function() {
  hello.value = hello.dataset.value;
});
hello.addEventListener('mouseout', function() {
  hello.value = '';
});
<input id="hello" value="Hello World" />

本文标签: javascriptHiding Text inside of an input elementStack Overflow