Content disappears immediately after form submitted and function runs
Asked Answered
M

2

6

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?

Marseilles answered 7/2, 2014 at 0:32 Comment(3)
The form is being submitted, so your code runs then the page refreshes. Incidentally, no values are submitted since none of the form controls have a name attribute.Glandule
EDIT: I added name attributes to the two form elements (the input tags, correct?). The same issue takes place thoughMarseilles
changing the tag from button to input worked for me :)Attentive
G
12

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.

Glandule answered 7/2, 2014 at 0:54 Comment(0)
R
1

Add this line inside the function:

event.preventDefault();
Rapparee answered 13/8 at 4:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.