views:

31

answers:

1

I have the following code which toggles the visibility of one of a pair of DropDownLists based on the selected radio button. This code works but my problem is that I have several sets of controls just like this on a single form. How can I use a single JavaScript Toggle() function, irrespective of the ID of the RadioButtonList that triggered it?

function Toggle() 
{
    var list = document.getElementById("produceDDL");
    var inputs = list.getElementsByTagName("input");

    var selected;
    for (var i = 0; i < inputs.length; i++) 
    {
        if (inputs[i].checked) 
        {
            selected = inputs[i];
            break;
        }
    }

    if (selected.value == 'Vegetables') 
    {
        div1.style.display = 'none';
        div2.style.display = 'block';
    }
    else 
    {
        div1.style.display = 'block';
        div2.style.display = 'none';
    }
}

    <asp:radiobuttonlist ID="produceDDL" OnClick="javascript:Toggle();" 
        RepeatDirection="Horizontal" runat="server">
        <asp:ListItem Selected="True">Fruit</asp:ListItem>
        <asp:ListItem>Vegetables</asp:ListItem>
    </asp:radiobuttonlist>

    <div id="div1">
        <asp:DropDownList ID="fruitDDL" Width="120" runat="server">
            <asp:ListItem>Select</asp:ListItem>
            <asp:ListItem>Apples</asp:ListItem>
            <asp:ListItem>Oranges</asp:ListItem>
        </asp:DropDownList>
    </div>

    <div id="div2" style="display:none;">
        <asp:DropDownList ID="vegDDL" Width="120" runat="server">
            <asp:ListItem>Select</asp:ListItem>
            <asp:ListItem>Onions</asp:ListItem>
            <asp:ListItem>Potatoes</asp:ListItem>
        </asp:DropDownList>
    </div>
+1  A: 

Let the radio button list pass itself as function argument.

OnClick="javascript:Toggle(this);"

Then you can replace

function Toggle() 
{
    var list = document.getElementById("produceDDL");
    // ...

by

function Toggle(list) 
{
    // ...

This way you can use OnClick="javascript:Toggle(this);" in other radio button lists.


By the way, the javascript: pseudoprotocol is unnecessary and the normal JavaScript naming convention is that function names should start with lowercase. I'd sanitize it as well :)

BalusC
Perfect, thanks! Marked as answer plus up vote :-)
IrishChieftain
You're welcome.
BalusC