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

如何修改JavaScript代码实现多组输入框与按钮的联动变色功能(支持jQuery实现)

Scaling Input-Button Interaction to Multiple Groups

Great question! Your original code works perfectly for a single input-button pair, but to make it handle any number of groups, we just need to refactor the logic to be reusable and properly associate each input with its corresponding button. Let's cover two solid approaches: vanilla JavaScript (no libraries) and jQuery.

Vanilla JavaScript Solution

The core idea here is to target groups of inputs and buttons (instead of single elements) and use DOM traversal to link each input to its paired button. Here's the full implementation:

HTML

<div class="input-group">
  <input class="form-input" placeholder="Username" />
  <button disabled class="form-btn" type="button">Submit</button>
</div>
<div class="input-group">
  <input class="form-input" placeholder="Email" />
  <button disabled class="form-btn" type="button">Submit</button>
</div>
<div class="input-group">
  <input class="form-input" placeholder="Phone Number" />
  <button disabled class="form-btn" type="button">Submit</button>
</div>

CSS

.input-group {
  margin: 15px 0;
}
.form-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 8px;
}
.form-btn {
  padding: 8px 18px;
  border: none;
  border-radius: 4px;
  color: white;
  background-color: grey;
  cursor: pointer;
  transition: background-color 0.2s;
}
.form-btn:disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

JavaScript

// Grab all input elements with our shared class
const allInputs = document.querySelectorAll('.form-input');

// Loop through each input to attach the keyup listener
allInputs.forEach(input => {
  input.addEventListener('keyup', function() {
    // Use DOM traversal to find the button in the same input group
    const pairedBtn = this.closest('.input-group').querySelector('.form-btn');
    const inputValue = this.value.trim(); // Trim to ignore empty spaces

    // Update button state and style based on input value
    if (inputValue === '') {
      pairedBtn.disabled = true;
      pairedBtn.style.backgroundColor = 'grey';
    } else {
      pairedBtn.disabled = false;
      pairedBtn.style.backgroundColor = 'orange';
    }
  });
});

Key Changes Explained:

  • We use querySelectorAll to get all inputs instead of a single one by ID.
  • closest('.input-group') lets us find the parent container of the current input, then querySelector('.form-btn') grabs the button specific to that group. This means you can add as many input-group blocks as you want without changing the JS.
  • trim() ensures that inputs with only spaces don't trigger the active button state.

jQuery Solution

If you're using jQuery, the code becomes even more concise thanks to its built-in DOM traversal methods. Here's the full implementation:

HTML (same as vanilla JS example)

<div class="input-group">
  <input class="form-input" placeholder="Username" />
  <button disabled class="form-btn" type="button">Submit</button>
</div>
<div class="input-group">
  <input class="form-input" placeholder="Email" />
  <button disabled class="form-btn" type="button">Submit</button>
</div>

CSS (same as vanilla JS example)

.input-group {
  margin: 15px 0;
}
.form-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 8px;
}
.form-btn {
  padding: 8px 18px;
  border: none;
  border-radius: 4px;
  color: white;
  background-color: grey;
  cursor: pointer;
  transition: background-color 0.2s;
}
.form-btn:disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

jQuery Code

$(document).ready(function() {
  // Attach keyup event to all inputs with the form-input class
  $('.form-input').on('keyup', function() {
    // Find the paired button using parent container traversal
    const $pairedBtn = $(this).closest('.input-group').find('.form-btn');
    const inputValue = $(this).val().trim();

    // Use jQuery's chainable methods to update button state and style
    if (inputValue === '') {
      $pairedBtn.prop('disabled', true).css('background-color', 'grey');
    } else {
      $pairedBtn.prop('disabled', false).css('background-color', 'orange');
    }
  });
});

Key Changes Explained:

  • jQuery's closest() and find() methods make linking the input to its button trivial.
  • Chainable methods like prop() and css() let us update multiple button properties in one line.
  • The code automatically handles any new input-group blocks added to the DOM (as long as they use the correct classes).

Alternative: Using Data Attributes for Flexible Pairing

If you don't want to rely on parent containers (e.g., inputs and buttons are in different parts of the DOM), you can use data-* attributes to explicitly link inputs to buttons:

HTML Example

<input class="form-input" data-target-btn="#username-btn" placeholder="Username" />
<button disabled id="username-btn" class="form-btn" type="button">Submit</button>

<input class="form-input" data-target-btn="#email-btn" placeholder="Email" />
<button disabled id="email-btn" class="form-btn" type="button">Submit</button>

Vanilla JS Adjustment

allInputs.forEach(input => {
  input.addEventListener('keyup', function() {
    const btnSelector = this.dataset.targetBtn;
    const pairedBtn = document.querySelector(btnSelector);
    const inputValue = this.value.trim();

    // Same state update logic as before
    if (inputValue === '') {
      pairedBtn.disabled = true;
      pairedBtn.style.backgroundColor = 'grey';
    } else {
      pairedBtn.disabled = false;
      pairedBtn.style.backgroundColor = 'orange';
    }
  });
});

This approach gives you full control over which input links to which button, regardless of their DOM structure.

内容的提问来源于stack exchange,提问作者Omkar Dhumal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:12:31