Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content disappears immediately after form submitted and function runs

I'm 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 hit submit, the javascript correctly executes the function, but the result (i.e. adding HEADING to the html) happens for a couple of milliseconds before disappearing and resetting to the original page before I had hit submit.

How do I make it so that the insertion of HEADING remains permanent?

like image 278
goelv Avatar asked Dec 15 '22 01:12

goelv


1 Answers

Move the listener to the form's submit handler. Have the function return false to stop submission:

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

Take the listener off the button:

<input type="submit">

Do not give it a name of submit as that will mask the form's submit method so you can't call it. Submit buttons only need a name if there are two or more on a form and you want to know which one was used to submit the form.

There is an error in your code, it's missing a closing double 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
};

This may or may not fix you issues, you haven't said what you are actually trying to do.

like image 115
RobG Avatar answered Feb 15 '23 22:02

RobG