how can i toggle a class on an element when an input has text in it?

To simplify your code, you can loop through the inputs and generate a single event handler instead of multiple. Plus you can call the input’s parent node to toggle the class on.

Plus you don’t want to toggle if you only want the label to show if the input has value.

I chose the input event as it covers paste as well as keyboard entry.

//Dynamic Form Label
const input = document.querySelectorAll('.custom-input');

input.forEach(function(el) {
  el.addEventListener('input', function(e) {
    if (e.target.value == "") {
      e.target.parentNode.classList.remove('form-group-with-value')
    } else {
      e.target.parentNode.classList.add('form-group-with-value')
    }

  });
});
.form-group {
  position: relative;
  min-height: 50px;
}

.form-group label {
  position: absolute;
  z-index: -1;
  transition: 0.3s;
  left: 5px;
}

.form-group-with-focus label {
  color: red;
}

.form-group-with-value label {
  transform: translateY(-80%);
}
<div class="form-group ">
  <label>Full Name</label>
  <input type="text" class="form-control custom-input" id="name" placeholder="Full Name">
</div>

<div class="form-group ">
  <label>Full Name</label>
  <input type="text" class="form-control custom-input" id="name" placeholder="Full Name">
</div>

<div class="form-group ">
  <label>Full Name</label>
  <input type="text" class="form-control custom-input" id="name" placeholder="Full Name">
</div>

<div class="form-group ">
  <label>Full Name</label>
  <input type="text" class="form-control custom-input" id="name" placeholder="Full Name">
</div>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top