jQuery 如何切换单选按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15105447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:22:53  来源:igfitidea点击:

How can I toggle radiobutton

javascriptjqueryhtml

提问by Hyman

Say this is my HTML:

说这是我的 HTML:

<input type="radio" name="rad" id="Radio0" checked="checked" />
<input type="radio" name="rad" id="Radio1" />
<input type="radio" name="rad" id="Radio2" />
<input type="radio" name="rad" id="Radio4" />
<input type="radio" name="rad" id="Radio3" />

As you can see the 1st radio button is checked. I need the radio button to function like toggle. For eg. If I again click on radio0, all radio buttons should be unchecked.

如您所见,第一个单选按钮已被选中。我需要单选按钮像切换一样起作用。例如。如果我再次单击radio0,则应取消选中所有单选按钮。

How can I achieve that?

我怎样才能做到这一点?

Update:I don't want any extra buttons. For eg. I could add a button and set the checked property for all radio buttons to be false. However, I don't want that. I only want my form to consist of these 4 radio buttons.

更新:我不想要任何额外的按钮。例如。我可以添加一个按钮并将所有单选按钮的checked 属性设置为false。然而,我不想那样。我只希望我的表单包含这 4 个单选按钮。

Update:Since most of the people don't understand what I want, let me try to rephrase- I want the radio button to function in toggle mode. I've given the same name to all radio buttons hence it's a group. Now I want the radiobuttons to toggle itself. Eg. if I click on radio0, it should get unchecked if it's checked and checked if it's unchecked.

更新:由于大多数人不明白我想要什么,让我尝试改写 - 我希望单选按钮在切换模式下运行。我为所有单选按钮赋予了相同的名称,因此它是一个组。现在我想让单选按钮自行切换。例如。如果我点击radio0,如果它被选中,它应该被取消选中,如果它未被选中,它应该被选中。

回答by Goran Mottram

The problem you'll find is that as soon a radio button is clicked its state is changed before you can check it. What I suggest is to add a custom attribute to keep track of each radio's previous state like so:

您会发现的问题是,一旦单击单选按钮,其状态就会在您检查之前发生更改。我的建议是添加一个自定义属性来跟踪每个收音机的先前状态,如下所示:

$(function(){
    $('input[name="rad"]').click(function(){
        var $radio = $(this);

        // if this was previously checked
        if ($radio.data('waschecked') == true)
        {
            $radio.prop('checked', false);
            $radio.data('waschecked', false);
        }
        else
            $radio.data('waschecked', true);

        // remove was checked from other radios
        $radio.siblings('input[name="rad"]').data('waschecked', false);
    });
});

You will also need to add this attribute to the initially checked radio markup

您还需要将此属性添加到最初检查的单选标记中

<input type="radio" name="rad" id="Radio0" checked="checked" data-waschecked="true" />

See demo here : http://jsfiddle.net/GoranMottram/VGPhD/2/

在此处查看演示:http: //jsfiddle.net/GoranMottram/VGPhD/2/

回答by Aashray

Once you give the name of 2 or more radio buttons as the same, they automatically become a group. In that group only one radio button can be checked. You have already achieved this.

一旦您将 2 个或更多单选按钮的名称命名为相同,它们将自动成为一个组。在该组中只能选中一个单选按钮。你已经做到了这一点。

回答by Yup.

I use an onClick() like the following for my custom radios:

我对我的自定义收音机使用如下所示的 onClick():

$(function(){
  // if selected already, deselect
  if ($(this).hasClass('selected') {
    $(this).prop('checked', false);
    $(this).removeClass('selected');
  }
  // else select
  else {
    $(this).prop('checked', true);
    $(this).addClass('selected');
  }
  // deselect sibling inputs
  $(this).siblings('input').prop('checked', false);
  $(this).siblings('input').removeClass('selected');
}

回答by soumitra

Using @Goran Mottram answer just tweaking it a bit to suit the case where radio buttons are not siblings.

使用@Goran Mottram 回答只是稍微调整一下以适应单选按钮不是兄弟的情况。

$(".accordian-radio-button").click(function(){
    var wasChecked = true;
    if($(this).data('waschecked') == true){
        $(this).prop('checked', false);
        wasChecked = false;
    }
    $('input[name="ac"]').data('waschecked', false);
    $(this).data('waschecked', wasChecked);
})

<input class="accordian-radio-button" data-waschecked="false" type="radio" name="ac" id="a1" />

回答by Manish Nayak

This code solved my issue

这段代码解决了我的问题

$("[type='radio']").on('click', function (e) {
    var previousValue = $(this).attr('previousValue');
    if (previousValue == 'true') {
        this.checked = false;
        $(this).attr('previousValue', this.checked);
    }
    else {
        this.checked = true;
        $(this).attr('previousValue', this.checked);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label >Toogle radio button example</label>
<br />
<input type="radio" name="toogle_me" value="mango"> Blue </input>
<input type="radio" name="toogle_me" value="kiwi"> Green </input>
<input type="radio" name="toogle_me" value="banana"> Yellow </input>
<input type="radio" name="toogle_me" value="orange"> Orange </input>

回答by Dr. Hakeem

I ran into this as well, after thinking about it and playing around with the various fiddles offered, I had a few dissatisfactions with the offered solutions.

我也遇到了这个问题,在考虑并尝试了提供的各种小提琴之后,我对提供的解决方案有些不满。

My main problem was the last line of the accepted answer, requiring a reset:

我的主要问题是接受答案的最后一行,需要重置:

// remove was checked from other radios
    $radio.siblings('input[name="rad"]').data('waschecked', false);

And since I'm not using jQuery, I'd have to loop over and evaluate the siblings myself, which isn't a huge deal, but seemed inelegant to me. But, there's no way around it with that method, because you're using the dataset as a storage of information.

因为我没有使用 jQuery,所以我必须自己循环并评估兄弟姐妹,这没什么大不了的,但对我来说似乎不雅。但是,使用该方法无法解决此问题,因为您将数据集用作信息存储。

After playing around, I realized is that the problem is that when a radio is clicked, it triggers the clicked event, and whatever function is attached to that click event completes itself beforethe function for the "onchange" event is ever evaluated, let alone called. So, if the click event "unchecks" the toggle, then no change event is ever fired.

玩了一圈之后,我意识到问题在于,当单击收音机时,它会触发 clicked 事件,并且附加到该单击事件的任何函数都会在“onchange”事件的函数被评估之前自行完成,更不用说叫。因此,如果单击事件“取消选中”切换,则不会触发任何更改事件

I've left my failed attempt here: https://codepen.io/RiverRockMedical/pen/daMGVJ

我把失败的尝试留在这里:https: //codepen.io/RiverRockMedical/pen/daMGVJ

But, if you could answer the question "will a change event happen after this click event?" then you could get a toggle working.

但是,如果你能回答这个问题“在这个点击事件之后会发生一个改变事件吗?” 那么你可以得到一个切换工作。

The solution I came up with can be seen at this pen: https://codepen.io/RiverRockMedical/pen/VgvdrY

我想出的解决方案可以在这支笔上看到:https: //codepen.io/RiverRockMedical/pen/VgvdrY

But basically is as follows:

但基本上如下:

function onClick(e) {
  e.dataset.toDo = 'uncheck';
  setTimeout(uncheck, 1, {
    event:'click',
    id:e.id,
    dataset:e.dataset
  });
}

So, on the click event, set a marker that the click has happened, and the use setTimeout() to create a pause that allows the onchange event to be evaluated and fire.

因此,在点击事件上,设置一个标记,表明点击已经发生,并使用 setTimeout() 创建一个暂停,允许评估和触发 onchange 事件。

function onChange(e) {
  e.dataset.toDo = 'leave';
}

If the onchange event fires, it undoes what was done by the onclick event.

如果 onchange 事件触发,它会撤消 onclick 事件所做的操作。

function uncheck(radio) {
  log('|');
  if (radio.event !== 'click') return;
  log('uncheck');
  if (radio.dataset.toDo === 'uncheck') {
    document.getElementById(radio.id).checked = false;
    radio.checked = false;
  } 
}

Then, when the uncheck function starts, it has the information of whether a change event followed the click event or not. If not, then the radio is unchecked, and functions as a toggle.

然后,当 uncheck 功能启动时,它具有更改事件是否跟随单击事件的信息。如果不是,则无线电未选中,并用作切换。

And, it's basically self-resetting, so I don't have to loop over all the radios and reset their datasets to the initial values at the end of the function.

而且,它基本上是自我重置的,所以我不必遍历所有无线电并将它们的数据集重置为函数结束时的初始值。

Now, I'm sure there's a cooler async/await way to do this that doesn't use setTimeout and would be even more elegant, but I'm still learning and I couldn't come up with it. Anyone else?

现在,我确信有一种更酷的 async/await 方法可以做到这一点,它不使用 setTimeout 并且会更优雅,但我仍在学习,我无法想出它。还有谁?

回答by Sagar Karn

<input type="radio" name="gender" id="male"onclick="getChecked(1)"><label for="male">Male</label>
<input type="radio" name="gender" id="female"onclick="getChecked(2)"><label for="female">female</label>
<script>
  var btnChecked = "";
  function getChecked(i) {
    if(btnChecked == i) {
      btnChecked = "";
      document.getElementsByTagName("input")[i-1].checked = false;
    }
    else btnChecked = i;
  }
</script>