How to dynamically disable radioButton group
Asked Answered
T

2

5

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.

Timetable answered 26/3, 2013 at 12:53 Comment(2)
You realise that this will (certainly seems to) create multiple elements with the same id?Panettone
only the name attribute is the sameTimetable
S
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

Schleswigholstein answered 26/3, 2013 at 12:57 Comment(0)
P
6

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.

Panettone answered 26/3, 2013 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.