【问题标题】:How to show two forms using two buttons in html如何在html中使用两个按钮显示两个表单
【发布时间】:2020-04-07 06:59:57
【问题描述】:

我想创建一个允许用户在数据库中创建密钥的页面。为此,用户必须首先在两个按钮之间进行选择。每个按钮显示不同的表单。

我的问题是下一个问题:我可以使用显示 ONE 表单的 ONE 按钮。这是来自https://stackoverflow.com/a/16196022/12533349 的代码:

HTML

<button id="some_id">Hide div</button>

<form id="some_form">

<form>

javascript

<script type="text/javascript">
    var theButton = document.getElementById('some_id');

    theButton.onclick = function() { 
        document.getElementById('some_form').style.visibility='hidden';   
    }

</script>

但我想做的是下一件事: 如果用户点击button_a,它会显示form_a,如果他点击button_b,但form_a > 显示,form_a 隐藏,form_b 显示。我希望它或多或少可以理解...

在结束这篇文章之前,我想补充一点:我使用 BootStrap 4 来构建我的 webapp。

【问题讨论】:

    标签: javascript html forms button bootstrap-4


    【解决方案1】:

    你可以使用这样的东西。

    var form1 = document.getElementById('form1');
    var form2 = document.getElementById('form2');
    // Hide the two forms when the page loads
    form2.style.display = "none";
    form1.style.display = "none";
    
    // Create a function that shows and hides the forms
    function showForm(x){
    if(x==1){ /* Check what form should be shown */
    form1.style.display = "block";
    form2.style.display = "none";
    }else if(x==2) {
    form1.style.display = "none";
    form2.style.display = "block";
    }
    }
    <button onclick="showForm(1)">Form 1</button><button onclick="showForm(2)">Form 2</button>
    <form id="form1">
    <h3>Form 1</h3>
    Example 1: <input placeholder="Example"/>
    </form>
    <form id="form2">
    <h3>Form 2</h3>
    Example 2: <input placeholder="Example"/>
    </form>

    在上面的代码中,我使用了style.display,但你也可以使用style.visibility

    【讨论】:

    • 非常感谢您的回答!我会在一段时间内尝试来自@mjm0813 的代码...顺便说一下,我怎样才能通过单击一个按钮来添加一个值 AB当用户点击 submit 按钮时到我的数据库?非常感谢!
    【解决方案2】:

    你在工作中停下来,你几乎达到了目标。 :)

    但是,回到我们,我认为使用类来添加和删除这样的方式更优雅:

    let theButton = document.getElementById('btn_id');
    let theButton2 = document.getElementById('btn_id_2');
    let element = document.getElementById('some_form');
    let element2 = document.getElementById('some_form_2');
    
    theButton.onclick = function() { 
       if(element.classList.contains('hidden')) {
       element.classList.remove('hidden');   
       element2.classList.add('hidden');   
       }
    }
    
    theButton2.onclick = function() { 
      if(element2.classList.contains('hidden')) {
         element2.classList.remove('hidden');   
         element.classList.add('hidden');   
      }
    }
    

    记得用可见性编写你的 .hidden 类:隐藏

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 2015-07-04
      • 1970-01-01
      • 2018-09-07
      相关资源
      最近更新 更多