Joshua Vertigo
Joshua Vertigo

Reputation: 29

Javascript - Button visible when has content in a input

I would like that when the user inserts information in a specific input text, another element becomes visible. My question looks study, but I'm new on JavaScript world, and I have tried searching on Google and here but I wasn't able to find anything.

Check out my code:

.hide {
  display: none;
}
<div>
  <label>Password:</label>
  <input type="password" id="pwInput">
  <a href="#" class="hide">Show password</a>
</div>

What I want is that the "Show password" anchor only shows when the password input has content inside.

Upvotes: 2

Views: 86

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44125

Just do this in JavaScript:

document.addEventListener("keydown", function() {
    if (document.getElementById("pwInput").value != "") {
        document.querySelector(".hide").style.display = "inline";
    }
    else {
        document.querySelector(".hide").style.display = "none";
    }
});
.hide {
  display: none;
}
<div>
  <label>Password:</label>
  <input type="password" id="pwInput">
  <a href="#" class="hide">Show password</a>
</div>

This will check every keydown if the input has any content, plus it'll work both ways e.g. if the user deletes the password then the anchor will go away.

Upvotes: 1

Phil
Phil

Reputation: 164832

Super simple option... use the input event handler on the <input> to toggle a class on it. You can then use an adjacent-sibling selector in your CSS to show or hide the <a>.

.hide {
  display: none;
}
.has-input + .hide {
  display: inline;
}
<div>
  <label>Password:</label>
  <input type="password" id="pwInput" 
         oninput="this.classList.toggle('has-input', this.value.trim())">
  <a href="#" class="hide">Show password</a>
</div>

If you're not a fan of inline event handlers, this is the unobtrusive equivalent

document.getElementById('pwInput').addEventListener('input', function(e) {
  this.classList.toggle('has-input', this.value.trim())
}, false)

Note, the force option on classList.toggle() doesn't work in IE. If you need to support it, try something like

this.classList[this.value.trim() ? 'add' : 'remove']('has-input')

Upvotes: 4

Related Questions