1

I have three text fields, I want to show the first and hide the second and third when option 1 is selected, and the opposite when option two is selected.

我做了以下事情:

<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/时,这部分没有按照我提到的方式工作

4

1 回答 1

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 修改后的解决方案来支持它!

于 2013-07-11T15:41:32.953 回答