使用JavaScript基于组合框的值隐藏和禁用元素

时间:2011-11-30 20:30:40

标签: javascript html

我有一个页面,根据组合框的值是否为假(否),应隐藏input框并禁用fieldset。当组合框的值更改为true(是)时,表单应显示input框并启用fieldset

这是我到目前为止所做的:

<html>
<head>
<title>combo</title>
<script language="javascript">
    function ToggleDisplay(Section, boolHide) {
        if (boolHide == true) {
            Section.style.display = "none";
        }
        else {
            Section.style.display = "";
        }
    }

    function disableElement(element, boolHide)
    {
        var input =
          document.getElementById(element).getElementsByTagName("input");
            for(var i = 0; i < input.length; i++)
            {
                input[i].setAttribute("disabled",boolHide);
            }
        }

        function hideShowElement(CurrentSection, OtherSection, DisableSection)
        {
            var sectionVal = CurrentSection.value;
                if (sectionVal == 0) {
                    ToggleDisplay(OtherSection, true);
                    //disableGroup (this.form, 'Radio1' , true);
                    disableElement(DisableSection, "true");
                }
                else {
                    ToggleDisplay(OtherSection, false);
                    //disableGroup (this.form, 'Radio1' , true);
                    disableElement(DisableSection, "false");
                }
            }
</script>
</head>
<body>
<form name="testForm" action="" method="post">
    Show Hidden Text?   <select name="cmbYN"
      onchange="hideShowElement(this, MyDIV, 'OptionGrp1');">
        <option value="0" selected="selected"></option>
        <option value="1">Yes</option>
        <option value="0">No</option>
    </select>

    <div id="MyDIV" style="display: none">
        My Hidden Text: <input name="Text1" type="text" />
    <br>
    </div>
    <fieldset id="OptionGrp1" name="Group1">
        Option Group<br><br>
        Option 1<input name="Radio1" type="radio" checked>
        Option 2<input name="Radio1" type="radio">
    </fieldset>
</form>
</body>
</html>

这会隐藏input框并禁用fieldset,但不会重新启用它们。

1 个答案:

答案 0 :(得分:3)

您应该将显示更改回之前的状态,通常是阻止。

        if (boolHide){
            Section.style.display = "none";
        }else {
            Section.style.display = "block";
        }

同样对于禁用,正确的方法是将disabled属性设置为disabled并在之后删除它:

            for(var i = 0; i < input.length; i++)
            { 
                if(boolHide){
                    input[i].setAttribute("disabled", "disabled");
                }else{
                    input[i].removeAttribute("disabled");
                }
            }