How in javascript to make a form disappear on submission

I have a form at the top of my html page which I want to have disappear after I submit the form. My code (below), while it temporarily hides the form, insists on the forming then becoming visible again. Any help would be appreciated.

Thanks,

Owen Walker

<!DOCTYPE html>
<html>
<body>

<form id="form" onsubmit="myFunction()">
  Enter name: <input type="text" name="fname">
  <input type="submit" value="Submit">
</form>

<div id="first_div" style="visibility:hidden">Second</div>

<script>
function myFunction() {
    alert("The form was submitted");
    document.getElementById("form" ).style.display = "none";  
    document.getElementById("first_div" ).style.visibility = "visible";
alert("after"); 
}
</script>

</body>
</html>

2 answers

  • answered 2017-06-17 19:32 j08691

    You're not doing anything to prevent your form from being submitted and reloading the page. Change the form line to:

    <form id="form" onsubmit="return myFunction()">
    

    and after the alert in your function add:

    return false;
    

  • answered 2017-06-17 19:32 Ankush Verma

    I would suggest you to use JQuery as it is a powerful tool for doing this type of stuffs without hassle... well you can do it in this way

        <!DOCTYPE html>
    <html>
    <body>
    
    <form id="form" onsubmit="myFunction()">
      Enter name: <input type="text" name="fname">
      <input type="submit" id="submit" value="Submit">
    </form>
    
    <div id="first_div" style="visibility:hidden">Second</div>
    
    <script>
    // using JQuery
     $(document).ready(function(){
            $("#submit").click(function(e){
                   e.preventDefault();
                   $("#form").submit();
                   $("#form").hide();
                   alert("Your form was successfully submitted");
                });
        });
    </script>
    
    </body>
    </html>
    

    ` note the use of preventDefault() to preventing it from submitting the form when you click submit.