Content disappears immediately after submitting the form and running the function

I am new to Javascript and HTML.

I have the following form in HTML:

<div id="form-select">
    <form id="date_form" action="" METHOD="POST">
        <datalist id="dates">
            <option value="February 7">February 7</option>
            <option value="February 14">February 14</option>
            <option value="February 21">February 21</option>
            <option value="February 28">February 28</option>
        </datalist>
        <input type="text" class="input" name="data" id="date" value="" list="dates" placeholder="pick a date"><br>
        <input type="submit" name="submit" onClick="myFunction()"/>
    </form>
 </div>

Here's the javascript in a file called script.js. The js file is linked in the header as 'script type = "text / javascript" src = "script.js':

function myFunction(){
   var input = document.getElementById("date").value;
   if(input==="February 7"){
      document.getElementById('w1').innerHTML = "<h2> HEADING </h2>;
   }
 };

When I fill out the form and click submit, javascript performs the function correctly, but the result (i.e. adding HEADING to the html) takes several milliseconds before disappearing and resetting the original page before I hit submit.

How do I keep the HEADING insert constant?

+3
source share
1 answer

Move the listener to the form submission handler. The function returns false to stop sending:

<form id="date_form" onsubmit="return myFunction();" ...>

:

<input type="submit">

submit, , . , , , .

, qoute:

function myFunction(){
   var input = document.getElementById("date").value;
   if(input==="February 7"){
      document.getElementById('w1').innerHTML = "<h2> HEADING </h2>";
   }
   return false; // to stop submission
};

, , .

+8

All Articles