I have a simple html with a input box(id=input) and a button(id=button) with 'Show' as button's text. I have wrote JavaScript to change show to hide on click and basic stuff.
Initinally , no button is displayed (as button display is none). What I want is as soon as I type anything in the input box Show button should display. How to do so in JavaScript?
Here is my JavaScript:-
let input = document.getElementById('input');
let btn = document.getElementById('button');
btn.addEventListener('click', () => {
if (btn.innerText === "SHOW") {
btn.innerText = "HIDE";
input.type = "text";
} else {
btn.innerText = "SHOW";
input.type = "password";
}
})
The below snippet shows and hides button according to the data that is inside the input
Also this is the event you were looking for https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event
document.querySelector("#pass").addEventListener('input',
(event) =>
{
if (document.querySelector("#pass").value.length === 0 ) {
document.querySelector("#btn").style.display = 'none';
} else {
document.querySelector("#btn").style.display = 'inline-block';
}
}
);
#btn { display: none; }
<input id="pass">
<button id="btn"> Show </button>
The below code should help you for the question you have asked (i.e. it will not automatically hide the button )
document.querySelector("#pass").addEventListener('input', () => {
document.querySelector("#btn").style.display = 'inline-block';
});
#btn {
display: none;
}
<input id="pass">
<button id="btn"> Show </button>
If I understood your question correctly, you should add a change eventlistener to input field. so that, when there is a change in input field, you can decide what to do.
input.addEventListener("change", function(){
if (input.value !== ""){
// do something
} else {
do something else
}
} )
The below snippet is the working model of what u asked 👇
please try to a avoid using innerText, innerHTML nor the on* attributes.
reference :
let input = document.getElementById('dataEntry')
let displayButton = document.getElementById('btn')
document.addEventListener('input', () => {
if (input.value.length === 0) {
displayButton.style.display = 'none';
} else {
displayButton.style.display = 'inline-block';
}
})
displayButton.addEventListener('click', (event) => {
if (event.target.textContent.toLowerCase() === 'hide') {
input.type = 'password'
event.target.textContent = 'Show'
} else {
input.type = 'text'
event.target.textContent = 'Hide'
}
})
.container {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#btn {
display: none;
}
<div class='container'>
<input type='text' id='dataEntry' placeholder='Enter your password' required/>
<button id='btn'>Hide</button>
</div>