首页 > 解决方案 > 如何在同一部分切换和隐藏两个不同的表单

问题描述

请帮助:我想在一个部分中有两个表单,如果单击一个按钮,第一个表单将可见,如果单击第二个按钮,则第二个表单将可见,而第一个表单隐藏,这将打开相同的部分。我如何实现这一目标

标签: javascriptjquerywordpressformsevents

解决方案


首先,很高兴包含您迄今为止尝试过的内容,也许还有一些您正在使用的代码,但无论如何我都会尽力帮助您。

我使用了来自 dyn-web.com 的一篇文章,该文章允许您将onClick处理程序分配给这对单选按钮。然后我简单地调整了处理程序来显示和隐藏各自的表单。

我已经评论了您将更改以添加自己的表单的代码部分,但目前每个表单只有一个测试输入和提交按钮。

<head>
  <script type="text/javascript">
    function switchForms() {
      var sz = document.forms['formSelector'].elements['form'];

      // loop through list
      
      for (var i=0, len=sz.length; i<len; i++) {
        sz[i].onclick = function() { // assign onclick handler  function to each
          // change the 'display' style property of the forms to show and hide them
          var display;
          var dntDisplay;
          if (this.value == 1) {
            display = 1;
            dntDisplay = 2;
          }else{
            display = 2;
            dntDisplay = 1;
          }
          document.getElementById('form' + display).style.display = "block";
          document.getElementById('form' + dntDisplay).style.display = "none";
        };
      }
    }
  </script>
</head>

<body onload="switchForms()">

  <form action="#" method="post" class="formSelector" id="formSelector">
    <fieldset>
      <legend>Change form on-click</legend>    
      <p>Select your form:&nbsp;
        <label><input type="radio" name="form" value="1" checked="checked" /> Form 1</label>
        <label><input type="radio" name="form" value="2"  /> Form 2</label>
      </p>
    </fieldset><br>
  </form>
    
  <form id="form1" method="post" action="">
    <h2>Form 1</h2>
    <!-- Insert any input fields you want for form 1 here -->
    <label>Input: <input type="text" name="total" class="num" value="" /></label>
    <button name="sbt=form1" type="submit">Submit</button>
  </form>
    
  <form id="form2" method="post" style="display:none" action="">
    <h2>Form 2</h2>
    <!-- Insert any input fields you want for form 2 here -->
    <label>Input: <input type="text" name="total" class="num" value="" /></label>
    <button name="sbt-form2" type="submit">Submit</button>
  </form>
    
</body>


推荐阅读