如何在IE中选择已禁用的单选按钮时保持单选按钮?

时间:2017-09-27 12:49:43

标签: javascript jquery html css internet-explorer

我在IE中遇到以下问题(9,10,11):我有一组单选按钮,其中一些必须被禁用,但仍然可以与表单一起提交。所以我想方设法使用以下功能:

var doNothing = function(event){
   event.preventDefault();
   event.stopPropagation();
}
var disableRadio = function($elem){
    $elem.bind('click.radiostate', doNothing);
    $elem.addClass('disabledRadioClass');
}

而不是添加disabled属性,并使用css:opacity:.5;设置相应按钮的样式,以便显示为已禁用。问题是,当我在IE中选择“禁用”单选按钮时,所选单选按钮变为未选中状态 - 即使它仍然将checked属性设置为已选中!这就是我的意思:

点击“禁用”电台(收音机2)之前:

enter image description here

之后:

enter image description here

没有任何选定的收音机。提交表单并刷新页面时,再次选择Radio 3。

我想要的是什么:当点击“自定义”禁用按钮时,所选按钮(例如本例中的Radio 3)应保持原样(如Chrome中),所以至少有一个单选按钮保持检查状态。

3 个答案:

答案 0 :(得分:1)

向radiobutton添加一个事件监听器



var currentRadio = 'r2'
var els = document.getElementsByClassName('radio')
var len = els.length;

while(len--){
  els[len].addEventListener('click',function(ev){
    if(ev.currentTarget.id == 'r1'){
      document.getElementById(currentRadio).checked = true;
    } else {
      currentRadio = ev.currentTarget.id
    }
    
  })
}
document
.querySelector('#r1')
.style.opacity = .5

<form>
<input class="radio" id="r1" name="name" value="radio1" type="radio">
<input class="radio" id="r2" name="name" value="radio2" type="radio">
<input class="radio" id="r3" name="name" value="radio3" type="radio">
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

不要将禁用属性添加到单选按钮,只需隐藏它们并在其位置添加虚拟禁用单选按钮,反之亦然,如果您希望它们再次启用。

答案 2 :(得分:0)

我改为使用了这个:

    var disableRadio = function($elem){
    /**
     * We need this in case of clicking on a disabled radio button: must know 
     * the previously checked radio button, so the selection stays as is and
     * does not disappear or move to the disabled one.
     * @type element
     */
    var $previouslySelectedRadioButton = $("input[name='"+$elem.attr("name")+"']:checked");
    /* Mouseup is executed before click, so by doing this we can get the 
     * previously checked radio before the disabled one gets the 
     * checked PROPERTY set to true. */
    $elem.bind('mouseup.radiostate', function(event){
        $previouslySelectedRadioButton = $("input[name='"+$(event.target).attr("name")+"']:checked");
    });
    //on click we return checked property to the previously selected radio
    $elem.bind('click.radiostate', function(){
        $previouslySelectedRadioButton.prop("checked", true);
        return false;
    });
    $elem.addClass('disabledRadioClass');
};

@Miguel Cabrera给了我一个主意。