简体   繁体   English

jQuery addClass 当组中的单选按钮被选中时

[英]jQuery addClass when a radio button in a group is selected

I have the following code:我有以下代码:

var selectedMarkerClass = 'was-selected';

$('.group_1').change(function() {
    $(this).addClass(selectedMarkerClass);

    if ($('.' + selectedMarkerClass).length == $('.group_1').length) {
        $('#2').removeClass('red');
    }
});

Here is the HTML in question:这是有问题的 HTML:

<input class="single_text_input group_1" type="text" name="primary_referral" />
<input class="single_text_input group_1" type="text" name="secondary_referral" />
<input class="group_1" type="radio" name="referral_open" value="Yes" /> Yes
<input class="group_1" type="radio" name="referral_open" value="No" /> No
<span id="2" class="red">Referral Group</span>

What is happening now is that both radio buttons in the group have to be changed in order for the class to be removed from the span .现在发生的情况是,必须更改组中的两个单选按钮才能将 class 从span中删除。 I would like it to work where only one of the radio buttons in the group has to be changed.我希望它在只需要更改组中的一个单选按钮的情况下工作。

Use the click event not change event.使用click事件而不是change事件。

$('.group_1').click(function() {
    $(this).addClass(selectedMarkerClass);

    if ($('.' + selectedMarkerClass).length == $('.group_1').length) {
        $('#2').removeClass('red');
    }
});

Update:更新:

if ($('.' + selectedMarkerClass).length == $('.group_1').length)

Is tripping you up.正在绊倒你。 You are removing the red class only if the selected class has been added to each radio and you can only add the selected class if you click each radio.仅当已将选定的 class 添加到每个无线电时,您才删除红色的 class,并且只有单击每个无线电才能添加选定的 class。

A better way would be:更好的方法是:

$('.group_1').click(function() {
    $('#2').removeClass('red');
});

Less code is often times better.更少的代码通常会更好。 You can't unselect a radio.您无法取消选择收音机。 So any click on the radios ensures at least one is clicked.因此,对收音机的任何点击都会确保至少有一个被点击。

Try it with click event instead.试试click事件。 You see the change take place after the second click because change gets fired after the first radio button loses focus.您会在第二次单击后看到更改发生,因为在第一个单选按钮失去焦点后会触发change

After both radio button changed, $('.' + selectedMarkerClass).length == 2 and $('.group_1').length == 4 because you are using .group_1 class for radio buttons and as well as for input[type=text] too.在两个单选按钮更改后, $('.' + selectedMarkerClass).length == 2$('.group_1').length == 4因为您使用.group_1 class 作为单选按钮以及输入[type =文本]也是。

need filter your radio button, use "[name=referral_open]" ,需要过滤您的单选按钮,使用"[name=referral_open]"

var selectedMarkerClass = 'was-selected';

$('.group_1').change(function () {
    $(this).addClass(selectedMarkerClass);

    if ($('.' + selectedMarkerClass).length == $('.group_1[name=referral_open]').length) {
        $('#2').removeClass('red');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM