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

如何用jQuery实现输入框值变化时动态切换对应Label的类

Solution to Toggle Label Class Based on Input Value

Here's a complete implementation that handles both initial page load (for pre-filled inputs) and real-time changes as the user types or modifies the input:

$(document).ready(function() {
    // Reusable function to handle label class toggle
    const toggleLabelState = function(inputElement) {
        const $input = $(inputElement);
        const $correspondingLabel = $input.siblings(`label[for="${$input.attr('id')}"]`);
        
        if ($input.val().trim() !== '') {
            $correspondingLabel.addClass('active'); // Replace 'active' with your target class
        } else {
            $correspondingLabel.removeClass('active');
        }
    };

    // Check all inputs on page load (handles pre-filled values)
    $('.input-field input').each(function() {
        toggleLabelState(this);
    });

    // Listen for input changes (covers typing, pasting, etc.)
    $('.input-field input').on('input', function() {
        toggleLabelState(this);
    });
});

Key Details:

  • Reusable Function: toggleLabelState takes an input element, finds its matching label using the for attribute (which links directly to the input's id), then adds/removes the class based on whether the input has a non-empty value.
  • Initial Check: The .each() loop runs on page load to handle any inputs that might already have values (like if the form is reloaded after a submission error).
  • Real-Time Updates: Using the input event instead of keyup ensures we catch all input changes—including pasting text with the mouse, using autocomplete, or clearing the field.
  • Class Customization: Replace 'active' with whatever class name you want to apply to the label when the input has content.

This implementation is efficient, targets exactly the corresponding label for each input, and works seamlessly with your existing HTML structure.

内容的提问来源于stack exchange,提问作者Bariq Dharmawan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:33:36