frederik
frederik

Reputation: 13

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>

Upvotes: 0

Views: 279

Answers (2)

MoPaMo
MoPaMo

Reputation: 684

Consider using display:block: https://www.w3schools.com/howto/howto_js_toggle_hide_show.asp


    function hide() {
        document.getElementById('form').style.display = "none";
    }
    function show(){
        document.getElementById('form').style.display = "block";
    }

Upvotes: 0

Quentin
Quentin

Reputation: 943108

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).

Upvotes: 1

Related Questions