繁体   English   中英

如何仅使用javascript和css隐藏和显示表单内的div

[英]how to hide and show a div that is inside of a form using only javascript and css

我有一个窗体,其中包含多个div,将某些输入字段组合在一起。 我想在页面初始加载时隐藏其中一些div(以及这些div中的输入字段)。 这对于CSS的display:none属性很简单。 然后,我想在用户单击“显示/隐藏”按钮时显示那些隐藏的div及其输入字段。 我为此项目仅使用javascript和CSS(无jquery)。

我有一个基本的javascript函数,只需单击一下按钮,即可交替隐藏(display:none)或显示(display:block)div。 当我在div不属于表单的测试页上使用该函数时,该函数运行良好。 但是,当我尝试对表单的divs部分(即内部)使用相同的功能时,它不起作用。 实际上,它似乎可以工作,但随后几乎立即恢复为显示设置的初始状态。 我感觉问题出在我的div位于表单内这一事实,但是我不明白为什么这会是一个问题。 我该怎么做才能更正此问题,以便表单内的div可以通过按钮的切换隐藏/显示。

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style>
#random {
    width: 600px;
    min-height: 50px;
    background-color:#E01418;
    color:#B5F0B9;
    display: block;
}
#hideshow {
    width: 600px;
    min-height: 50px;
    background-color:#223FCD;
    color:#F2D595;
    display:block;
}
</style>
</head>

<body>

<form id="myform" name="myform" method="post" action="">
    <div id="random">
        <input type="text" id="firstname" name="firstname" placeholder="firstname">
        <input type="text" id="lastname" name="lastname" placeholder="lastname">
        <input type="email" id="email" name="email" placeholder="email">
    </div>

    <div id="hideshow">
        <input type="password" id="password" name="password" placeholder="password">
        <input type="text" id="address" name="address" placeholder="address">
        <input type="text" id="phone" name="phone" placeholder="phone">
    </div>
    <input type="submit" id="submit" name="submit" value="Update">
    <button id="togglehideshow">Hide/Show</button>
</form>

<script>

var button = document.getElementById('togglehideshow'); 

button.onclick = function() {
    var div = document.getElementById('hideshow');
    if (div.style.display !== 'none') {
        div.style.display = 'none';
    }
    else {
        div.style.display = 'block';
    }
};

</script>

</body>

</html>

最后一件事-我正在使用的按钮不是表单的提交按钮。 我只是不想让任何人对此感到困惑。 谢谢您的帮助!

为显示和隐藏div的按钮添加type = button。

<button type="button" id="togglehideshow">Hide/Show</button>

这是因为按钮在隐藏div之后尝试提交表单。

暂无
暂无

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

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