Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically disable radioButton group

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.

like image 364
Jacob Avatar asked Dec 04 '22 11:12

Jacob


2 Answers

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

like image 50
Rohan Kumar Avatar answered Dec 23 '22 13:12

Rohan Kumar


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.

like image 25
David Thomas Avatar answered Dec 23 '22 14:12

David Thomas