使用Javascript隐藏和显示下拉菜单和文本字段

时间:2013-04-07 08:23:02

标签: javascript html

在下面的下拉菜单中,当用户选择操作号时,我希望显示下一个下拉菜单

<select id="OperationType" onChange="check(this);">
 <option value="OpNo">Operation No</option>
 <option value="OpEmp">Employee No</option>
</select>

<select id=OperationNos>
 <option value="1001">1001</option>
 <option value="1002">1002</option>
</select>

如果用户选择员工编号,我希望隐藏最后一个下拉菜单,并显示以下文本字段:

<input type='text'>

我所做的是我放下以下脚本,但它不会隐藏这两个元素:

function check(elem) {
    document.getElementById('OperationType').disabled = !elem.selectedIndex;
}

它只禁用了它。我希望它是隐形的。 感谢

3 个答案:

答案 0 :(得分:6)

将一个style =“display:none”添加到您的OperationNos中:

您无需将this传递给check()。

如果选择“OpNo”,则修改您的函数以切换此css属性:

function check() {
    var dropdown = document.getElementById("OperationType");
    var current_value = dropdown.options[dropdown.selectedIndex].value;

    if (current_value == "OpNo") {
        document.getElementById("OperationNos").style.display = "block";
    }
    else {
        document.getElementById("OperationNos").style.display = "none";
    }
}

示例:http://jsfiddle.net/2pna2/

答案 1 :(得分:1)

看那个:

var ot = document.getElementById('OperationType');
ot.disabled = !elem.selectedIndex;
ot.style.display = 'none'; // not rendered
//ot.style.visisbility = 'hidden'; // rendered but just invisble it's there

答案 2 :(得分:1)

使用: -

function hideshow()
{
var s1= document.getElementById('OperationType');
var s2= document.getElementById('OperationNos');

if( s1.options[s1.selectedIndex].text=="Operation No")
{
s2.style.visibility = 'visible';
document.getElementById('t1').style.visibility = 'hidden';
}
if( s1.options[s1.selectedIndex].text=="Employee No")
{
s2.style.visibility = 'hidden';
document.getElementById('t1').style.visibility = 'visible';
}
}
function hide()

{

document.getElementById('t1').style.visibility = 'hidden';
}

Html代码: -

<body onload="hide()">

<select id="OperationType" onChange="hideshow()">
 <option value="OpNo">Operation No</option>
 <option value="OpEmp">Employee No</option>
</select>

<select id="OperationNos">
 <option value="1001">1001</option>
 <option value="1002">1002</option>
</select>

<input type="text" id="t1" />
</body>