Javascript jQuery选中/取消选中单选按钮onclick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6191621/
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-23 20:39:08  来源:igfitidea点击:

jQuery check/uncheck radio button onclick

javascriptjqueryradio

提问by DiegoP.

I have this code to check/uncheck a radio button onclick.

我有这个代码来检查/取消选中单选按钮 onclick。

I know it is not good for the UI, but I need this.

我知道这对 UI 不利,但我需要这个。

$('#radioinstant').click(function() {     
  var checked = $(this).attr('checked', true);
  if(checked){ 
    $(this).attr('checked', false);
  }
  else{ 
    $(this).attr('checked', true);
  }
});

The above function is not working.

上述功能不起作用。

If I click on the button, nothing changes. It remain checked. Why? Where is the error? I am not a jQuery expert. I am on jQuery 1.3.2

如果我单击按钮,则没有任何变化。它保持检查。为什么?错误在哪里?我不是 jQuery 专家。我在 jQuery 1.3.2

Just to be clear #radioinstantis the ID of the radio button.

需要明确的#radioinstant是单选按钮的 ID。

采纳答案by Briguy37

If all you want to do is have a checkbox that checks, don't worry about doing it with JQuery. That is default functionality of a checkbox on click. However, if you want to do additional things, you can add them with JQuery. Prior to jQuery 1.9, you can use use $(this).attr('checked');to get the value instead of $(this).attr('checked', true);, as the second will set the value.

如果您想要做的只是有一个检查复选框,请不要担心用 JQuery 来做。这是单击复选框的默认功能。但是,如果您想做其他事情,可以使用 JQuery 添加它们。在 jQuery 1.9 之前,您可以使用 use$(this).attr('checked');来获取值而不是$(this).attr('checked', true);,因为第二个将设置值。

Hereis a fiddle demonstration that shows the default checkbox functionality vs. what you are doing with JQuery.

是一个小提琴演示,显示了默认复选框功能与您使用 JQuery 执行的操作。

Note: After JQuery 1.6, you should use $(this).prop;instead of $(this).attrin all three places (thanks @Whatevo for pointing this out and see here for further details).

注意: 在 JQuery 1.6 之后,您应该在所有三个地方使用$(this).prop;而不是$(this).attr(感谢@Whatevo 指出这一点,并在此处查看更多详细信息)。

UPDATE:

更新:

Sorry, missed the requirement that it had to be a radio button. You still may want to consider the checkbox, but hereis the updated code for the radio input version. It works by setting the previousValueas an attribute on the checkbox, as I don't think propis supported in 1.3.2. You could also do this in a scoped variable, as some people don't like setting random attributes on fields. Hereis the new example.

抱歉,错过了必须是单选按钮的要求。您可能仍然需要考虑复选框,但这里是无线电输入版本的更新代码。它的工作原理是将previousValue复选框设置为属性,因为我认为prop1.3.2不支持。您也可以在范围变量中执行此操作,因为有些人不喜欢在字段上设置随机属性。 是新的例子。

UPDATE 2:

更新 2:

As Josh pointed out, the previous solution only worked with one radio button. Here's a function that makes a group of radios deselectable by their name, and a fiddle:

正如 Josh 指出的那样,之前的解决方案仅适用于一个单选按钮。这是一个功能,可以通过名称和小提琴取消选择一组收音机:

var makeRadiosDeselectableByName = function(name){
    $('input[name=' + name + ']').click(function() {
        if($(this).attr('previousValue') == 'true'){
            $(this).attr('checked', false)
        } else {
            $('input[name=' + name + ']').attr('previousValue', false);
        }

        $(this).attr('previousValue', $(this).attr('checked'));
    });
};

回答by Jurrie

I have expanded on the previous suggestions. This works for me, with multiple radios coupled by the same name.

我已经扩展了之前的建议。这对我有用,多个无线电以相同的名称耦合。

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

  if (previousValue == 'checked')
  {
    $(this).removeAttr('checked');
    $(this).attr('previousValue', false);
  }
  else
  {
    $("input[name="+name+"]:radio").attr('previousValue', false);
    $(this).attr('previousValue', 'checked');
  }
});

回答by manji

Instead of getting the checked value you are setting it with:

您设置的不是获取检查值:

var checked = $(this).attr('checked', true);

To properly get it:

要正确获取它:

var checked = $(this).attr('checked');

A working solution (with multiple radio buttons having different values):

一个有效的解决方案(多个单选按钮具有不同的值):

// select radio buttons group (same name)
var radioButtons = $("input[type='radio'][name='rr']");
// save initial ckecked states
var radioStates = {};
$.each(radioButtons, function(index, rd) {
    radioStates[rd.value] = $(rd).is(':checked');
});

// handle click event
radioButtons.click(function() {

    // check/unchek radio button
    var val = $(this).val();  
    $(this).prop('checked', (radioStates[val] = !radioStates[val]));    

    // update other buttons checked state
    $.each(radioButtons, function(index, rd) {
        if(rd.value !== val) {
            radioStates[rd.value] = false; 
        }
    });
});

P.S.:$().attrshould be used instead of $().propfor jquery < 1.6

PS:$().attr应该用于代替$().propjquery < 1.6

Demo: jsFiddle

演示:jsFiddle

回答by Slavik Meltser

Best and shortest solution. It will work for any group of radios (with the same name).

最佳和最短的解决方案。它适用于任何无线电组(具有相同的名称)。

$(document).ready(function(){
    $("input:radio:checked").data("chk",true);
    $("input:radio").click(function(){
        $("input[name='"+$(this).attr("name")+"']:radio").not(this).removeData("chk");
        $(this).data("chk",!$(this).data("chk"));
        $(this).prop("checked",$(this).data("chk"));
        $(this).button('refresh'); // in case you change the radio elements dynamically
    });
});

More information, here.

更多信息,请点击此处

Enjoy.

享受。

回答by jeeber

I believe this is the problem: If you have more than one radio button, and one of them is clicked, there is no way to deselect all of them. What is needed is a "none or only one" selector, so checkboxes would not be appropriate. You could have a "clear" button or something like that to deselect all, but it would be nice to just click the selected radio button to deselect it and go back to the "none" state, so you don't clutter your UI with an extra control.

我相信这是问题所在:如果您有多个单选按钮,并且单击了其中一个按钮,则无法取消选择所有这些按钮。需要的是“无或只有一个”选择器,因此复选框不合适。您可以有一个“清除”按钮或类似的东西来取消选择所有内容,但最好只需单击选定的单选按钮取消选择它并返回“无”状态,这样您就不会使您的 UI 杂乱无章额外的控制。

The problem with using a click handler is that by the time it is called, the radio button is already checked. You don't know if this is the initial click or a second click on an already checked radio button. So I'm using two event handlers, mousedown to set the previous state, then the click handler as used above:

使用点击处理程序的问题在于,当它被调用时,单选按钮已经被选中。您不知道这是第一次单击还是第二次单击已选中的单选按钮。所以我使用了两个事件处理程序,mousedown 来设置以前的状态,然后是上面使用的点击处理程序:

$("input[name=myRadioGroup]").mousedown(function () 
{
    $(this).attr('previous-value', $(this).prop('checked'));
});

$("input[name=myRadioGroup]").click(function () 
{
    var previousValue = $(this).attr('previous-value');

    if (previousValue == 'true')
        $(this).prop('checked', false);
});

回答by Nabil Kadimi

toggleAttr()is provided by this very nice and tiny plugin.

toggleAttr()这个非常漂亮和小巧的插件提供

Sample code

示例代码

$('#my_radio').click(function() {
    $(this).toggleAttr('checked');
});

/**
 * toggleAttr Plugin
 */
jQuery.fn.toggleAttr = function(attr) {
    return this.each(function() {
        var $this = $(this);
        $this.attr(attr) ? $this.removeAttr(attr) : $this.attr(attr, attr);
    });
};

Even more fun, demo

更有趣的是,演示

You can use place your radio button inside label or button tags and do some nice things.

您可以使用将单选按钮放在标签或按钮标签内并做一些不错的事情。

回答by Mithun Sreedharan

Improved version of answer from Jurrie

Jurrie 答案的改进版本

$('#myRadio').off('click').on('click', function() {
  if ($(this).data('checked')) {
    $(this).removeAttr('checked');
    $(this).data('checked', false);
  } else {
    $(this).data('checked', true);
  }
});

Live Demo

现场演示

回答by mick88

Having tested some of the above solutions which did not work for me 100%, I decided to create my own. It creates new click listeners after a radio button is clicked:

在测试了上述一些对我来说 100% 不起作用的解决方案后,我决定创建自己的解决方案。单击单选按钮后,它会创建新的单击侦听器:

/**
 * Radio select toggler
 * enables radio buttons to be toggled when clicked
 * Created by Michal on 09/05/2016.
 */

var radios = $('input[type=radio]');

/**
 * Adds click listeners to all checkboxes to unselect checkbox if it was checked already
 */
function updateCheckboxes() {
    radios.unbind('click');
    radios.filter(':checked').click(function () {
        $(this).prop('checked', false);
    });
    radios.click(function () {
        updateCheckboxes();
    });
}

updateCheckboxes();

回答by Aarti Goyal

$(document).ready(function(){ $("input:radio:checked").data("chk",true);

$(document).ready(function(){ $("input:radio:checked").data("chk",true);

$("input:radio").click(function(){
    $("input[name='"+$(this).attr("name")+"']:radio").not(this).removeData("chk");

    $(this).data("chk",!$(this).data("chk"));

    $(this).prop("checked",$(this).data("chk"));
});

});

});

回答by Harold

Simplest solution. For both Radio and Checkboxes.

最简单的解决方案。对于单选框和复选框。

$('body').on('click', 'input[type="checkbox"]', function(){
    if ($(this).attr('checked')){
        $( this ).attr( 'checked', false);
    } else {
        $( this ).attr( 'checked', true);
    }
});
$('body').on('click', 'input[type="radio"]', function(){
    var name = $(this).attr('name');
    $("input[name="+name+"]:radio").attr('checked', false);
    $( this ).attr( 'checked', true);
});