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

使用jQuery实现单选按钮组切换父级<label>元素的类属性

Hey there! Let's sort out this radio button label class toggle problem for you. The core issue here is that when you select a new radio in the group, you need to reset all other labels first before applying the selected class to the new one—here's how to do it properly with both vanilla JS and jQuery options:

Vanilla JavaScript Solution

First, let's assume your HTML structure looks something like this (all radio buttons share the same name attribute to form a group):

<label class="sample">
  <input type="radio" name="radio-group" value="option1"> Option 1
</label>
<label class="sample">
  <input type="radio" name="radio-group" value="option2"> Option 2
</label>
<label class="sample">
  <input type="radio" name="radio-group" value="option3"> Option 3
</label>

Add this JavaScript to handle the class toggling correctly:

// Grab all radio buttons in the target group
const radioGroup = document.querySelectorAll('input[name="radio-group"]');

// Attach a change event listener to each radio button
radioGroup.forEach(radio => {
  radio.addEventListener('change', function() {
    // Step 1: Remove the 'selected' class from ALL labels in the group
    radioGroup.forEach(item => {
      item.parentElement.classList.remove('selected');
    });
    // Step 2: Add the 'selected' class to the parent label of the currently checked radio
    this.parentElement.classList.add('selected');
  });
});
jQuery Solution

If you're using jQuery in your project, this shorter version will work just as well:

// Target the radio group and listen for change events
$('input[name="radio-group"]').on('change', function() {
  // Reset all labels in the group by removing 'selected'
  $('input[name="radio-group"]').parent().removeClass('selected');
  // Apply 'selected' to the parent label of the newly checked radio
  $(this).parent().addClass('selected');
});

How this works

The key fix here is that we first clear the selected class from every label in the radio group whenever any radio is changed. Then we only apply the class to the label containing the newly selected radio. This ensures only one label has the selected class at a time, which is exactly what you need for radio button groups.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:25:26