我有三个文本字段,我想显示第一个字段并在选择选项1时隐藏第二个和第三个字段,而选择选项2时则相反。
我做了以下事情:
<script language="javascript">
function hola(x) {
if(x == 1) {
document.getElementById("div1").style.visibility="visible";
document.getElementById("div2").style.visibility="hidden";
}
if(x == 2) {
document.getElementById("div1").style.visibility="hidden";
document.getElementById("div2").style.visibility="visible";
}
}
</script>
<body onload='hola(1)'>
<label class="field6" for="shower_times">how many showers each takes per day: </label>
<SELECT name="shower_times" onChange="hola(this.value)">
<OPTION value="1">1</OPTION>
<OPTION value="2">2</OPTION>
</SELECT>
<div id="div1">
<BR>
<label class="field6" for="hour"> hour of the shower: </label><input type="text" name="hour" class="input">
</div>
<div id="div2">
<label class="field6" for="hour1">hour of first shower: </label><input type="text" name="hour1" class="input">
<BR>
<label class="field6" for="hour2">hour of second shower: </label><input type="text" name="hour2" class="input">
</div>
当我更改选项时,它正在工作,但问题是,在开始时我希望它只显示第一个字段,这就是我使用的原因
<body onload='hola(1)'>
但它不起作用,它在开头显示所有三个。
代码似乎单独工作, 但是当我把它添加到其他代码http://jsfiddle.net/3YZBm/1/时,这一部分并没有像我提到的那样工作
答案 0 :(得分:1)
如果你选择使用纯JS,你可以做这样的事情......
HTML(稍加修改)......
<label class="field6" for="shower_times">how many showers each takes per day: </label>
<SELECT name="shower_times" id="mselect" onChange="hola();">
<OPTION value="1">1</OPTION>
<OPTION value="2">2</OPTION>
</SELECT>
<div id="div1">
<BR>
<label class="field6" for="hour"> hour of the shower: </label><input type="text" name="hour" class="input">
</div>
<div id="div2">
<label class="field6" for="hour1">hour of first shower: </label><input type="text" name="hour1" class="input">
<BR>
<label class="field6" for="hour2">hour of second shower: </label><input type="text" name="hour2" class="input">
</div>
</div>
CSS(默认选择隐藏2个字段,默认选择1)...
#div2 {
display:none;
}
由Maggie修改的JS ......
function hola() {
var mselect = document.getElementById("mselect");
var mselectvalue = mselect.options[mselect.selectedIndex].value;
var mdivone = document.getElementById("div1");
var mdivtwo = document.getElementById("div2");
if (mselectvalue == 2) {
mdivtwo.style.display = "block";
mdivone.style.display = "none";
}
else {
mdivtwo.style.display = "none";
mdivone.style.display = "block";
}
}
和Maggie的修改后的解决方案to back了!