如何隐藏表单并仅在选中时显示

How to hide a form and show up only when selected?

本文关键字:显示 表单 何隐藏 隐藏      更新时间:2023-09-26

我想构建我的第一个程序。昨天我开始编码,我无法停止,但我在onchange功能方面遇到了问题。我希望<form id="squareA">仅在我的选项列表中选择Square时才显示。另一个列表也是如此。我还没有制作他们的表格,因为我被困在squareA。

这是我的代码。

<script>
  function myShapes() {
    var a1 = document.getElementById("shapes").value;
    if(a1.value == option.value) {
      document.getElementById("square").value = ("squareA");
    } else {
      document.getElementById("square").disabled = true;
    }
  }
}
</script>
<legend>Calculate Dimension</legend>
<select id="shapes" onchange="myShapes">
  <option selected="selected" value="none">Select Shape</option>
  <option onselect="mySquare" id="square" value="Square">Square</option>
  <option onselect="myRect" id="rect" value="Rectangle">Rectangle</option>
  <option onselect="myComb" id="comb" value="Combined">Combined</option>
  <option  onselect="myStrap" id="strap" value="Strap">Strap</option>
  <option  onselect="myTrap" id="trap" value="Trapezoidal">Trapezoidal</option>
</select>
<form id="squareA">
  <div disabled="disabled" id="disa">
    <input id="squareD" type="text" placeholder="Dimension"/> by
    <input id="squareD2" type="text" placeholder="Dimension"/>
  </div>
</form>
</fieldset>

长行内是不起作用或错误的代码。

你需要在 onchange 属性中调用函数,然后在更改处理程序中检查值并设置表单的显示值

function myShapes() {
  /*On change check the value of the select and based on it set the display css value to either none or block*/
  document.getElementById('squareA').style.display = document.getElementById('shapes').value == 'Square' ? 'block' : 'none'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<legend>Calculate Dimension</legend>
<select id="shapes" onchange="myShapes()">
  <!--Need to call the function here, id add () at the end-->
  <option selected="selected" value="none">Select Shape</option>
  <option value="Square">Square</option>
  <option value="Rectangle">Rectangle</option>
  <option value="Combined">Combined</option>
  <option value="Strap">Strap</option>
  <option value="Trapezoidal">Trapezoidal</option>
</select>
<form id="squareA" style="display:none;">
  <!--Hide the form on page load-->
  <div disabled="disabled" id="disa">
    <input id="squareD" type="text" placeholder="Dimension" />by
    <input id="squareD2" type="text" placeholder="Dimension" />
  </div>
</form>