当用户从前一个元素中选择一个选项时,如何显示隐藏元素

时间:2014-05-22 02:55:24

标签: javascript html forms

我正在为作业创建表单。如何在选择不同问题的值时出现新问题?例如,

<label for="Etype">*What would you like to enrol in?</label>
<select id="Etype" name="Etype">
    <option value="">Select...</option>
    <option value="Camp">Camp</option>
    <option value="Class">Class</option>
</select>
</fieldset>

并选择&#34; class&#34;先前隐藏的问题是在前一个问题下面提出的问题&#34;类的类型?&#34;

2 个答案:

答案 0 :(得分:1)

将它放在身体结束标记之前:

<script>
document.getElementById('Etype').onchange = function() {
    var isSelected = this.options[this.selectedIndex].value == 'Class';
    document.getElementById('hiddenField').style.display = isSelected ? 'block':'none';
};
</script>

假设隐藏元素具有ID&#39; hiddenField&#39;:

<div id="hiddenField" style="display:none;">
    Place the hidden field, labels, etc. here
</div>

答案 1 :(得分:1)

HTML

<fieldset>
<label for="Etype">*What would you like to enrol in?</label>
       <select id="Etype" onchange="show_hidden(this.value)" name="Etype">
          <option value="">Select...</option>
          <option value="Camp">Camp</option>
          <option value="Class">Class</option>
      </select>

<div id="class">
Type of class : <input type="text" name="class_text" />
</div><!-- #class -->
<div id="camp">
 Type of Camp <input type="text" name="camp_text" />
</div><!-- #camp -->
</fieldset>

CSS

#class, #camp{display:none;}

的Javascript

function show_hidden(str)
{
   // if first option was selected, hide both the hidden fields
   if(str == '')
   {
      document.getElementById('class').style.display = 'none';
      document.getElementById('camp').style.display = 'none';
   }
   // if class was selected, show the class fields and hide camp fields if visible
   else if(str == 'Class')
   {
      document.getElementById('class').style.display = 'block';
      document.getElementById('camp').style.display = 'none';
   }
   // if camp was selected, show the camp fields and hide class fields if visible
   else if(str == 'Camp')
   {
      document.getElementById('camp').style.display = 'block';
      document.getElementById('class').style.display = 'none';
   }
}

DEMO