0

I'm trying to hide and element inside a form but it's not working. here's my code:

<style> .hide { visibility: hidden; display: none; } </style> </head> <body> <form> <input type="submit" id="show" value="Show" /> <input type="submit" value="Hide" id="hide" /> </form> <script type="text/javascript"> /* save the 2 nodes to variables */ var button = document.getElementById("show"), target = document.getElementById("hide"); /* define what we want to do in a function */ function hide(){ target.setAttribute("class","hide"); } /* add the CSS class when the button is clicked */ button.addEventListener("click", hide, false); </script> </body> 
  • But it works if I take it out of the form container. Please explain...
1
  • 1
    Please avoid using submit when you are not submitting. Use button rather. Commented May 28, 2014 at 6:52

2 Answers 2

2

The reason the code isn't working, is because you're using submit buttons.
They submit the form, making the page reload, preventing your JavaScript from doing it's thing.

Replace:

<input type="submit" id="show" value="Show" /> <input type="submit" value="Hide" id="hide" /> 

With:

<input type="button" id="show" value="Show" /> <input type="button" value="Hide" id="hide" /> 

Working example

When you click the "Show" button, it hides the "hide" button, just as the code says it should.

Sign up to request clarification or add additional context in comments.

Comments

2

I think it actually works. You can check the fiddle (the code is the same)

Before submission hide button gets hidden.

Maybe your problem is you don't realize that if you put buttons inside the form you're actually sending. When you press button it sets target class to hide and submit the form, thus rerendering (without the hide class).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.