You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

当文本框有内容时修改表单提交按钮样式——Jade/Pug问题

Fixing CSS Class Not Applying to Submit Button in Pug/Jade Form Mixin

Hey there, I spot the exact issue right away—you're modifying the button's class the wrong way in your JavaScript! Let me break this down for you:

The Root Problem

You’re using btn.class = 'butOn' to change the button’s CSS class, but that’s not how DOM elements work. The class property on a DOM element isn’t directly accessible like that—you’re just adding a custom property to the JS object instead of updating the actual DOM’s class attribute. That’s why your CSS styles aren’t kicking in at all. Also, your logic has a small bug: you’re setting butOn in both the enabled and disabled branches, when you probably want butOff for the disabled state.

Fixed Code

First, update your Pug mixin to set the initial correct class for the disabled button:

mixin myForm()
  form(action="/tweet/add" method="POST" class="formclassname")
    textarea( name='text' id='textarea' maxlength="300" placeholder='What\'s happening?' )
    // Add butOff to initial class since button starts disabled
    input( type="submit" id="button" value="Send It" class="button butOff" disabled = true )
  script.
    var btn = document.getElementById('button');
    var inpt = document.getElementById('textarea');
    inpt.addEventListener("input", function(){
      // Use trim() to ignore empty whitespace
      const hasContent = this.value.trim() !== '';
      if (hasContent) {
        btn.disabled = false;
        btn.classList.remove('butOff');
        btn.classList.add('butOn');
        console.log('button enabled');
      } else {
        btn.disabled = true;
        btn.classList.remove('butOn');
        btn.classList.add('butOff');
        console.log('button disabled');
      }
    })

Even Cleaner Version (Optional)

You can simplify the class toggling using classList.toggle() with a second argument, which adds/removes the class based on a boolean:

inpt.addEventListener("input", function(){
  const hasContent = this.value.trim() !== '';
  btn.disabled = !hasContent;
  btn.classList.toggle('butOn', hasContent);
  btn.classList.toggle('butOff', !hasContent);
  console.log(hasContent ? 'button enabled' : 'button disabled');
})

Why This Works

  • classList is the standard API for manipulating DOM element classes—it directly updates the element’s class attribute in the DOM, so your CSS rules will pick up the changes immediately.
  • Adding trim() ensures that users can’t just type spaces to enable the button, which is a common edge case.
  • Setting the initial butOff class makes sure the button starts with the correct disabled styling right when the page loads.

内容的提问来源于stack exchange,提问作者Axle Max

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:30:36