如何用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:
toggleLabelStatetakes an input element, finds its matching label using theforattribute (which links directly to the input'sid), 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
inputevent instead ofkeyupensures 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
相关产品推荐
相关产品推荐

