编辑模式下为选中选项对应的label添加active类的实现方案
Got it, let's sort out this issue for you. The problem with your current code is that $('label.control-lbl') targets all labels with that class on the page, which is why the active class gets added everywhere. We need to tie the label directly to its associated <select> element so we only modify the correct one.
Here's the Solution:
We'll use the standard form association between <label> and <select> (via the for attribute on the label matching the id of the select) to target the exact label we need. We'll also handle both the initial page load (for your edit mode pre-selected options) and user selection changes.
Updated jQuery Code:
$(document).ready(function() { // Initialize label state on page load $('select.form-control').each(function() { const $select = $(this); // Find the label linked to this select using the "for" attribute const $targetLabel = $(`label[for="${$select.attr('id')}"]`); const selectedOptionText = $select.find('option:selected').text().trim(); // Toggle active class based on selected option if (selectedOptionText.length > 0) { $targetLabel.addClass('active'); } else { $targetLabel.removeClass('active'); } }); // Update label state when user changes the selection $('select.form-control').on('change', function() { const $select = $(this); const $targetLabel = $(`label[for="${$select.attr('id')}"]`); const selectedOptionText = $select.find('option:selected').text().trim(); if (selectedOptionText.length > 0) { $targetLabel.addClass('active'); } else { $targetLabel.removeClass('active'); } }); });
Why This Works:
- Precise Label Targeting: Using
label[for="${$select.attr('id')}"]ensures we only grab the label that's explicitly linked to the current<select>(your label hasfor="login_type"which matches the select'sid="login_type"—perfect for this). - Initialization Handling: The
.each()loop runs on page load, so any pre-selected options in edit mode will immediately trigger the correctactiveclass on their label. - Dynamic Updates: The
changeevent listener makes sure the label updates in real-time when the user picks a different option.
Key Fix From Your Original Code:
Instead of selecting all .control-lbl labels globally, we now target only the label associated with the specific <select> that has the selected option. This prevents the class from being applied to every label on the page.
内容的提问来源于stack exchange,提问作者user9595480

