Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

javascript - Set HTML hide attribute with js

I want to set a hide HTML attribute with JS but it is reseting itself after 1ms. Does anyone know how to set the hide attribute and remove it.

<body>
    <form method="post" id="form">
        <input type="text" name="text" id="text" ><br>
        <button onclick="hide()">True</button>
        <button onclick="show()">false</button>
        <input type="submit" name="submit">
    </form>
</body>
<script type="text/javascript">
    function hide() {
        document.getElementById('form').hidden = true;
    }
    function show(){
        document.getElementById('form').hidden = false;
    }
</script>
question from:https://stackoverflow.com/questions/65904336/set-html-hide-attribute-with-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are calling hide() when you click a submit button inside a form.

  1. The JavaScript runs
  2. The element is hidden
  3. The form submits
  4. A new document is loaded and rendered (and it isn't hidden in the new document).

Don't use a submit button unless you actually want to submit the form.

<button type="button" ...>

If you do want to submit the form then you'll need to set the hidden attribute in the new page. You could do that with server-side code that reads the form data (and you'll need to set a name and value for the hide submit button so the data can be picked up by that page).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...