Javascript 在 html 中隐藏/显示表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7401010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:09:00  来源:igfitidea点击:

Hide/Show form in html?

javascripthtmlcssforms

提问by Spike Lee

I'm new to html and im trying to hide/show forms if the user ticks a box a form appears below it.

我是 html 的新手,我试图隐藏/显示表单,如果用户勾选一个框,一个表单出现在它下面。

I have a form e.g.

我有一个表格,例如

Name : 
Username : 
Add More Users: (tickbox) 

If the user ticks the 'Add More Users', another form with the fields 'Name,Username,Add More Users' appears below it. How is this possible?

如果用户勾选“添加更多用户”,则会在其下方显示另一个包含“名称、用户名、添加更多用户”字段的表单。这怎么可能?

回答by Simone

HTML

HTML

<input type="checkbox" onclick="display(this)">Add more users</input>
<div id="yourDiv"> ...other forms... </div>

JavaScript

JavaScript

   function display(e){
    if (e.checked)
        document.getElementById('yourDiv').style.display = 'block';
    else
        document.getElementById('yourDiv').style.display = 'none';
    }


An even better way to do this(thanks to What)

一个更好的方法来做到这一点(感谢What

HTML

HTML

<input id="more" type="checkbox">Add More Users</input>
<div id="yourDiv"> ...other form... </div>

JavaScript

JavaScript

window.onload = function () {
    document.getElementById('more').onclick = function () {
        if (this.checked)
            document.getElementById('yourDiv').style.display = 'block';
        else
            document.getElementById('yourDiv').style.display = 'none';  
    }
}

回答by Ahmad

You will need to use scripts for that.

您将需要为此使用脚本。

First of all put the form you want to Show/Hide inside a <div id="myForm">tag and enclose it with

首先把你想要显示/隐藏的表单放在一个<div id="myForm">标签中,然后用

Then use jQuery http://www.jquery.com(download the jquery library and link it to your page and add an event at the loading of the page to run a function to check if the combo box is checked then execute:

然后使用 jQuery http://www.jquery.com(下载 jquery 库并将其链接到您的页面,并在页面加载时添加一个事件以运行一个函数来检查组合框是否被选中,然后执行:

("#myForm").toggle();

回答by ahmetertem

You can use .clone() and .append() (requires jQuery). You have give name attribute like

您可以使用 .clone() 和 .append() (需要 jQuery)。你给了 name 属性,比如

<input type="text" name="test[]" />