NeedHelp Guy
NeedHelp Guy

Reputation: 11

javascript cannot propertly display document.forms element

My issue is the following - my browser does not display the myForm1 function properly. What happens is that the "namedItem" just appears quickly on the screen when clicking the try button and then disappears

It does this only with the form element. The one below does exactly what is required from it. Here is my code:

 <!DOCTYPE html>
 <html>
  <head></head>
  <body>
   <form id="myForm">
     Tenancy: <input type="number" name="tenam">
   <button onclick="myForm1()">Try it</button>
   </form>
   <p>Simple text</p>
 <button onclick="simpText()">Show</button>
 <div id="show">
 </div>
 <script type="text/javascript">
   function myForm1() {
   var x = document.forms.namedItem("myForm").innerHTML;
   document.getElementById("show").innerHTML = x;
   }
   function simpText () {
     var x = document.getElementsByTagName("p")[0].innerHTML;
     document.getElementById("show").innerHTML = x;
   }
  </script>
 </body>
 </html>

Upvotes: 1

Views: 94

Answers (1)

j08691
j08691

Reputation: 207901

You're doing nothing to stop your form from being submitted when clicking the button element, and a button element's default type is submit. So when you click the button in your form, the page is being reloaded and the change lost. You can fix this by adding a type like button to your button:

<button onclick="myForm1()" type="button">Try it</button>

jsFiddle example

Upvotes: 2

Related Questions