选中并取消选中具有不同名称的单选按钮

时间:2014-01-21 12:26:49

标签: jquery html

我知道如果我们有相同的名字,那么单选按钮会交替变化。但我希望在点击时检查和取消选中它,与其他无线电没有任何关系。

js小提琴:

http://jsfiddle.net/Jk6Sk/1/

HTML

<input type="radio" name="test1" value="male" checked>Male<br>
<input type="radio" name="test2" value="female" checked>Female

js(我试过):

$("input[type=radio]").on("click",function(){
    if(!$(this).is(":checked")){
        $(this).prop("checked",true);
    }else{
        $(this).prop("checked",false);
    }
});

注意:

它应该像复选框一样工作(可能吗??)

2 个答案:

答案 0 :(得分:5)

您可以uncheck所有check当前单选按钮点击事件。我会使用一个类来分组这些单选按钮,以避免不希望在页面上包含单选按钮并具体。

<强> Live Demo

$("input[type=radio]").on("click",function(){   
    $("input[type=radio]").prop("checked",false);
     $(this).prop("checked",true);
});
根据评论

编辑,您需要保持单选按钮选中状态以切换。

<强> Live Demo

$("input[type=radio]").data('checkedStatus', true);
$("input[type=radio]").on("click",function(){   
    if($(this).data('checkedStatus') == true)
    {
        this.checked = false;
        $(this).data('checkedStatus', false);
    }
    else
    {
         $(this).data('checkedStatus', true);
        this.checked = true;
    }
});

答案 1 :(得分:3)

你可以这样做:

<强> jquery的:

var radioStatus = false;
$.each($('input[type=radio]'),function(){
    this.radioStatus = $(this).prop("checked") || false;
    $(this).data("status",this.radioStatus);
    $(this).click(function(){
        this.radioStatus = !$(this).data("status")
        $(this).prop("checked",this.radioStatus);
        $(this).data("status",this.radioStatus);
    })
})

<强> Fiddle Demo

相关问题