繁体   English   中英

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

[英]How to show a hidden element when a user selects an option from a previous element

我正在为作业创建表格。 在选择其他问题的值时,如何使新问题出现? 例如,

<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>

在选择“班级”之后,在先前询问“班级类型”的问题下方会显示一个先前隐藏的问题。

将其放在您的身体闭合标签之前:

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

假设隐藏元素的ID为“ hiddenField”:

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

的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;}

Java脚本

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';
   }
}

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM