最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to dynamically disable radioButton group - Stack Overflow

programmeradmin4浏览0评论

I create one element in my radioGroup like this:

var selectorLay1 = document.createElement('input');
        var selectorLay1Atributes = {
            'type': 'radio',
            'class': "selectorLay1",
            'id': "radioLay1",
            'name': "layouts",
            'onchange': "mv.createLayout(1,1)"};

I have different elements like this. But they all have the same name: 'layouts'. How to find all of this elements and disable them dynamically.

I create one element in my radioGroup like this:

var selectorLay1 = document.createElement('input');
        var selectorLay1Atributes = {
            'type': 'radio',
            'class': "selectorLay1",
            'id': "radioLay1",
            'name': "layouts",
            'onchange': "mv.createLayout(1,1)"};

I have different elements like this. But they all have the same name: 'layouts'. How to find all of this elements and disable them dynamically.

Share Improve this question edited Jul 14, 2014 at 3:33 tshepang 12.5k25 gold badges97 silver badges139 bronze badges asked Mar 26, 2013 at 12:53 JacobJacob 4,03123 gold badges91 silver badges151 bronze badges 2
  • You realise that this will (certainly seems to) create multiple elements with the same id? – David Thomas Commented Mar 26, 2013 at 12:56
  • only the name attribute is the same – Jacob Commented Mar 26, 2013 at 13:08
Add a comment  | 

2 Answers 2

Reset to default 12

Try this:

var radios = document.getElementsByName('layouts');
for (var i = 0, r=radios, l=r.length; i < l;  i++){
    r[i].disabled = true;
}

Read https://developer.mozilla.org/en-US/docs/DOM/document.getElementsByName for getElementsByName

I'd suggest:

var inputs = document.getElementsByName('layouts');
for (var i = 0, len = inputs.length; i<len; i++){
    inputs[i].disabled = true;
}

Simple demo.

This will select the relevant elements with the name of layouts, and then, in the for {...} loop, iterate over those elements and set the disabled property.

Using a simple function approach:

function disableByName(elName){
    var els = document.getElementsByName(elName);
    if (els !== null){
        for (var i = 0, len = els.length; i<len; i++){
            els[i].disabled = true;
        }
    }
}

var button = document.getElementById('radioDisable');

button.addEventListener('click',function(e){
    e.preventDefault();
    disableByName('layouts');
}, false);

Simple demo.

Or, if you'd prefer, you can extend the Object prototype to allow you to directly disable those elements returned by the document.getElementsByName() selector:

Object.prototype.disable = function(){
    var that = this;
    for (var i = 0, len = that.length; i<len; i++){
        that[i].disabled = true;
    }
    return that;
};

document.getElementsByName('layouts').disable();

Simple demo.

发布评论

评论列表(0)

  1. 暂无评论