简体   繁体   中英

Disable radio button list item with Javascript

I'm attempting to disable a radio button from an asp RadioButtonList using Javascript. Here is what I have:

<asp:RadioButton ID="rbPlanner" runat="server" onclick="deselectRadioListItem('P');" />

which calls this client javascript onClick...

    function deselectRadioListItem(radioValue) {
        var clientID = ('<%= rblSummaryOptions.ClientID %>');
        for (i = 0; i < '<%= rblSummaryOptions.Items.Count %>'; i++) {
            if (document.getElementById(clientID + "_" + i.toString()).value == radioValue) {
                (clientID + "_" + i.toString()).disabled === true;
            }
            else
            {
                (clientID + "_" + i.toString()).disabled === false;
            }
        }
    }

Everything appears to be working correctly(fires, iterates, if-statements work) however, the radiobutton control is not becoming disabled, even though the logic is hit. What am I missing? Help is much appreciated, thank you!

The === operator is used for comparison. You need to use = .

function deselectRadioListItem(radioValue) {
    var clientID = ('<%= rblSummaryOptions.ClientID %>');
    for (i = 0; i < '<%= rblSummaryOptions.Items.Count %>'; i++) {
        if (document.getElementById(clientID + "_" + i.toString()).value == radioValue) {
            document.getElementById(clientID + "_" + i.toString()).disabled = true;
        }
        else
        {
            document.getElementById(clientID + "_" + i.toString()).disabled = false;
        }
    }
}

Or cleaned up a tiny bit:

function deselectRadioListItem(radioValue) {
    var clientID = ('<%= rblSummaryOptions.ClientID %>');
    for (i = 0; i < '<%= rblSummaryOptions.Items.Count %>'; i++) {
        var objCurrentRdo = document.getElementById(clientID + "_" + i.toString());

        if (objCurrentRdo.value == radioValue)
            objCurrentRdo.disabled = true;
        else
            objCurrentRdo.disabled = false;
    }
}​

Additional Information: Check out Comparison Operators on MDN.

this is for sure wrong.

(clientID + "_" + i.toString()).disabled === true;

maybe you won to type

document.getElementById(clientID + "_" + i.toString()).disabled = true;

or even better

function deselectRadioListItem(radioValue) {
        var clientID = ('<%= rblSummaryOptions.ClientID %>');
        for (i = 0; i < <%= rblSummaryOptions.Items.Count %>; i++) {
                document.getElementById(clientID + "_" + i).disabled = 
              document.getElementById(clientID + "_" + i).value == radioValue;
        }
    }

you have some bugs here...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM