0

This is code to render a form mixin in Node/Express (using Jade/Pug as the template engine)

My goal is to disable the button when there is no text in the textarea and enable the button when there is text persent. It works except the css classes (for visual styling) aren't getting applied.

My best guess is that I am changing the class of an object in memory (var btn) and not on the actual object in the DOM.

I can't work out how to do that. Can anyone help please?

mixin myForm()

  form(action="/tweet/add" method="POST" class="formclassname")

    textarea(
      name='text' 
      id='textarea' 
      maxlength="300" 
      placeholder='What\'s happening?'
    )

    input(
      type="submit" 
      id="button" 
      value="Send It" 
      class="button"
      disabled = true
    )

 script.

    var btn = document.getElementById('button');
    var inpt = document.getElementById('textarea');

    inpt.addEventListener("input", function(){
      if (this.value != '') {
        btn.disabled = false;
        btn.class = 'butOn';
        console.log('button enabled');
      } 
      else {
          btn.class = 'butOn';
          console.log('button disabled');
      }
})

CSS

.button{
  /* Style Font */
  text-align: center;
  text-decoration: none;
  font-weight: bold;
  color: rgb(255, 255, 255);

  /* Style "button" */
  background-color: rgba(0, 166, 255);
  border-radius: 25px;
  border: 2px solid rgb(0, 166, 255, 0.6);
  /* Position the button */
  padding: 10px 20px 10px 20px;
  margin: 5px 10px 5px 10px;
 }

.butOn {
  background-color: #1dec0a;
}

.butOff {
  background-color: rgb(147, 208, 249);
}
Axle Max
  • 785
  • 1
  • 14
  • 23

1 Answers1

1

Typical! I spend 30 minutes typing the question then find an answer 5 seconds later.

Leaving this here to help others.

How can I change an element's class with JavaScript?

TLDR... classList.remove and .add as follows

   script.
      var btn = document.getElementById('button');
      var inpt = document.getElementById('textarea');
      inpt.addEventListener("input", function(){
        if (this.value != '') {
          btn.disabled = false;
          btn.classList.remove('butOff');
          console.log(btn);
        } 
        else {
          btn.classList.add('butOff');
          btn.disabled = true;
          console.log('no text present');
        }
      })
Axle Max
  • 785
  • 1
  • 14
  • 23