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

| 我有这段代码可以检查/取消选中单选按钮onclick。 我知道这对UI不利,但是我需要这样做。
$(\'#radioinstant\').click(function() {     
  var checked = $(this).attr(\'checked\', true);
  if(checked){ 
    $(this).attr(\'checked\', false);
  }
  else{ 
    $(this).attr(\'checked\', true);
  }
});
上面的功能不起作用。 如果我单击按钮,则没有任何改变。它保持选中状态。为什么?错误在哪里?我不是jQuery专家。我在jQuery 1.3.2上 为了清楚起见,“ 1”是单选按钮的ID。     
已邀请:
        如果您要做的只是选中一个复选框,请不要担心使用JQuery。这是单击复选框的默认功能。但是,如果要执行其他操作,则可以使用JQuery添加它们。在jQuery 1.9之前,您可以使用
$(this).attr(\'checked\');
代替
$(this).attr(\'checked\', true);
来获取值,因为第二个将设置该值。 这是一个小提琴演示,显示了默认复选框功能与您对JQuery所做的操作。 注意:在JQuery 1.6之后,您应该在所有三个位置使用
$(this).prop;
而不是
$(this).attr
(感谢@Whatevo指出这一点,并在此处查看更多详细信息)。 更新: 抱歉,错过了必须为单选按钮的要求。您仍可能需要考虑该复选框,但这是单选输入版本的更新代码。它通过在复选框上将setting6设置为属性来工作,因为我不认为1.3.2支持ѭ7。您也可以在范围变量中执行此操作,因为有些人不喜欢在字段上设置随机属性。这是新示例。 更新2: 正如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\'));
    });
};
    
        我已经扩展了先前的建议。 这对我来说很有效,可以使用多个同名电台。
$(\"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\');
  }
});
    
        不用获取检查值,而是用以下方法进行设置:
var checked = $(this).attr(\'checked\', true);
要正确获取它:
var checked = $(this).attr(\'checked\');
一个有效的解决方案(具有多个具有不同值的单选按钮):
// 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; 
        }
    });
});
附言:jquery <1.6时,应使用
$().attr
代替
$().prop
演示:jsFiddle     
        最佳和最短的解决方案。它适用于任何一组无线电(具有相同名称)。
$(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
    });
});
更多信息,在这里。 请享用。     
        我相信这是问题所在:如果您有多个单选按钮,并且单击了其中一个,则无法取消选择所有这些按钮。所需的是一个“无或只有一个”选择器,因此复选框将不合适。您可能有一个“清除”按钮或类似的按钮来取消全部选择,但是最好只单击选定的单选按钮以取消选择它,然后返回到“无”状态,因此您不必使用额外的控件会使您的用户界面混乱。 使用单击处理程序的问题在于,在调用该处理程序时,单选按钮已被选中。您不知道这是单击还是选中已选中的单选按钮。因此,我使用了两个事件处理程序,将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);
});
    
        very17ѭ是由这个非常小巧的插件提供的。 样例代码
$(\'#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);
    });
};
演示更有趣 您可以使用将单选按钮放置在标签或按钮标签内的方法,并做一些不错的事情。     
        Jurrie的答案的改进版本
$(\'#myRadio\').off(\'click\').on(\'click\', function() {
  if ($(this).data(\'checked\')) {
    $(this).removeAttr(\'checked\');
    $(this).data(\'checked\', false);
  } else {
    $(this).data(\'checked\', true);
  }
});
现场演示     
        在测试了上述一些对我而言100%无效的解决方案之后,我决定创建自己的解决方案。单击单选按钮后,它将创建新的Click侦听器:
/**
 * 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();
    
        $(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\"));
});
});     
        -编辑- 肯定看起来您的代码正在迫使单选输入的行为类似于复选框输入。您可能会考虑只使用复选框输入而无需jQuery。但是,如果要强制执行操作(如@manji所述),则需要将值存储在点击处理程序外部,然后将每次点击的值设置为与当时相反的值。 @manji \的答案是正确的,我只想补充一下,您应该缓存jQuery对象,而不是重新查询DOM:
var $radio = $(\"#radioinstant\"),
    isChecked = $radio.attr(\"checked\");

$radio.click(function() {

    isChecked = !isChecked;
    $(this).attr(\"checked\", isChecked);

});
    
        DiegoP, 我遇到了同样的麻烦,直到我意识到在删除该属性之前,该复选框不会消失。这意味着即使将检查值设为假,它也将保留在那里。 因此,请使用removeAttr()函数并删除选中的attrib,它将正常工作。     
如果您仍然想获得更多答案,我发现这适用于所有单选按钮:
<script type=\"text/javascript\">
        jQuery(document).ready(function ($){
                    var allRadios = $(\'input[type=radio]\')
                    var radioChecked;

                    var setCurrent = 
                                    function(e) {
                                        var obj = e.target;

                                        radioChecked = $(obj).attr(\'checked\');
                                 }

                    var setCheck = 
                                function(e) {

                                    if (e.type == \'keypress\' && e.charCode != 32) {
                                        return false;
                                    }

                                    var obj = e.target;

                         if (radioChecked) {
                         $(obj).attr(\'checked\', false);
                         } else {
                         $(obj).attr(\'checked\', true);
                         }
                             }    

                    $.each(allRadios, function(i, val){        
                         var label = $(\'label[for=\' + $(this).attr(\"id\") + \']\');

                     $(this).bind(\'mousedown keydown\', function(e){
                            setCurrent(e);
                        });

                        label.bind(\'mousedown keydown\', function(e){
                            e.target = $(\'#\' + $(this).attr(\"for\"));
                            setCurrent(e);
                        });

                     $(this).bind(\'click\', function(e){
                            setCheck(e);    
                        });

                    });
        });
</script>
    
        此功能将对所有单选按钮添加一个选中/未选中状态
jQuery(document).ready(function(){
jQuery(\':radio\').click(function()
{
if ((jQuery(this).attr(\'checked\') == \'checked\') && (jQuery(this).attr(\'class\') == \'checked\'))
{   
    jQuery(this).attr(\'class\',\'unchecked\');
    jQuery(this).removeAttr(\'checked\');
} else {
jQuery(this).attr(\'class\',\'checked\');
}//or any element you want

});
});
    
        我拍了https://stackoverflow.com/a/13575528/80353并像这样修改了它
$(document).ready(function() {

        $(\'body\').on(\'click\', \'input[type=\"radio\"]\', function() {
            changeCheckedAttributes($(this));
        });
        function changeCheckedAttributes(elt) {
            $(\"input[name=\'\"+$(elt).attr(\"name\")+\"\']:radio\").not($(elt)).removeData(\"chk\");
            $(\"input[name=\'\"+$(elt).attr(\"name\")+\"\']:radio\").not($(elt)).removeAttr(\"checked\");
            $(\"input[name=\'\"+$(elt).attr(\"name\")+\"\']:radio\").not($(elt)).prop(\"checked\", false);
            $(elt).data(\"chk\",!$(elt).data(\"chk\"));
            $(elt).prop(\"checked\", true);
            $(elt).attr(\"checked\", $(elt).data(\"chk\"));
        }

    });
    
        我建议这样做:
$(\'input[type=\"radio\"].toggle\').click(function () {
    var $rb = $(this);

    if ($rb.val() === \'on\') {
        $rb.val(\'off\');
        this.checked = false;
    }
    else {
        $rb.val(\'on\');
        this.checked = true;
    }
});
您的HTML如下所示:
<input type=\"radio\" class=\"toggle\" value=\"off\" />
    
        我有一个相关但不同的场景。以下是我在做什么: 注意:选择主单选按钮时,选择/取消选择类“ containerRadio \”的所有单选按钮的代码。 码
        $(\'#selectAllWorkLot\').click (function ()
        {

              var previousValue = $(this).attr(\'previousValue\');

              if (previousValue == \'checked\')
              {
                resetRadioButtonForSelectAll();

                //Unselect All
                unSelectAllContainerRadioButtons();
              }
              else
              {
                $(this).attr(\'previousValue\', \'checked\');

                //Select All
                selectAllContainerRadioButtons();
              }
        });


        function resetRadioButtonForSelectAll()
        {
            $(\'#selectAllWorkLot\').removeAttr(\'checked\');
            $(\'#selectAllWorkLot\').attr(\'previousValue\', false);
            //$(\'#selectAllWorkLot\').prop(\'checked\', false);
        }


        function selectAllContainerRadioButtons()
        {
            $(\'.containerRadio\').prop(\'checked\', true);
        }

        function unSelectAllContainerRadioButtons()
        {
            $(\'.containerRadio\').prop(\'checked\', false);
        }
    
        我遇到了一个相关的问题-我必须根据从下拉列表中的选择打开一个下拉对话框,我将显示一个或两个单选按钮。一次只能激活一个单选按钮。 选项1将显示两个单选按钮,并选择第一个单选 选项2将显示第二个单选按钮并被选中。 该脚本有时会工作一段时间,它会注入选中的内容,但复选框仍未选中 我使用jQuery
.prop()
,似乎
jquery .prop() .attr()
在使用attr或prop时,单选按钮有些复杂。因此,我要做的是根据“选择值”触发单选按钮的单击。 这就解决了使用attr或prop或使用冗长的代码的需求。
myForm = $(\"#myForm\");

if (argument === \'multiple\') {
            myForm.find(\'#radio1\').parent(\'li\').hide();
            myForm.find(\'#radio2\').trigger(\'click\');
    }
    else{
        myForm.find(\'#radio1\').trigger(\'click\');
         myForm.find(\'#radio1\').parent(\'li\').show();
    }
不知道这是否是最佳做法,但它像魅力一样工作     
        这是一个简单的解决方案,希望对您有所帮助。这是一个改善答案的简单示例。
$(\'[type=\"radio\"]\').click(function () {

            if ($(this).attr(\'checked\')) {

                $(this).removeAttr(\'checked\');
                $(this).prop(\'checked\',false);

            } else {

                $(this).attr(\'checked\', \'checked\');

            }
        });
演示版 对不起,为时已晚.. :)     
        最后一种解决方案是对我有用的解决方案。我在使用Undefined和object object时遇到问题,或者总是返回false,然后总是返回true,但是这种解决方案在检查和取消检查时都有效。 此代码在单击时显示字段,而在未选中时隐藏字段:
$(\"#new_blah\").click(function(){
   if ($(this).attr(\'checked\')) {

            $(this).removeAttr(\'checked\');
    var radioValue = $(this).prop(\'checked\',false);
    // alert(\"Your are a rb inside 1- \" + radioValue);
    // hide the fields is the  radio button is no     
    $(\"#new_blah1\").closest(\"tr\").hide();
    $(\"#new_blah2\").closest(\"tr\").hide();

    } 
    else {

    var radioValue =  $(this).attr(\'checked\', \'checked\');
    // alert(\"Your are a rb inside 2 - \" + radioValue);
    // show the fields   when radio button is set to  yes
    $(\"#new_blah1\").closest(\"tr\").show();
    $(\"#new_blah2\").closest(\"tr\").show();

}
    
        我从这个问题尝试过的解决方案对我不起作用。在部分起作用的答案中,我仍然发现我必须单击两次以前未选中的单选按钮,才能再次对其进行检查。我目前正在使用jQuery 3+。 在尝试使用数据属性或其他属性使它起作用之后,我终于通过使用类来解决了。 对于您检查的无线电输入,将其指定为“ѭ34”类,例如:
<input type=\"radio\" name=\"likes_cats\" value=\"Meow\" class=\"checked\" checked>
这是jQuery:
$(\'input[type=\"radio\"]\').click(function() {
    var name = $(this).attr(\'name\');

    if ($(this).hasClass(\'checked\')) {
        $(this).prop(\'checked\', false);
        $(this).removeClass(\'checked\');
    }
    else {
        $(\'input[name=\"\'+name+\'\"]\').removeClass(\'checked\');
        $(this).addClass(\'checked\');
    }
});
    
        如果您单击并使用,并且仅检查是否选中了单选,然后取消选择,则将永远不会选中单选。因此,最简单的方法就是使用这样的类名:
if($(this).hasClass(\'alreadyChecked\')) {//it is already checked
        $(\'.myRadios\').removeClass(\'alreadyChecked\');//remove from all radios
        $(this).prop(\'checked\', false);//deselect this
    }
    else {
        $(\'.myRadios\').removeClass(\'alreadyChecked\');//remove from all
        $(this).addClass(\'alreadyChecked\');//add to only this
    }
    
        最简单的解决方案。对于单选框和复选框。
$(\'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);
});
    

要回复问题请先登录注册