html - My JavaScript form validation function is called two times -


i trying print value form when user submits function blank value returned.

here javascript code:

var login = new function() {     var name = null ;      this.validation = function()     {         this.name = document.getelementbyid("username").value;         console.log(this.name);          document.getelementbyid("demo").innerhtml = this.name;     }; }; 

and html form :

<body>   <div class="container">     <div class="col-md-8">        <div class="starter-template">         <h1>login javascript</h1>         <p class="lead">please enter following details</p>         <h1 id="demo"></h1>         <form name="form" onsubmit="return login.validation();" action="#" method="post">           <div class="form-group">             <label for="exampleinputemail1">username</label>             <input type="text" name="username" class="form-control" id="username" placeholder="please enter username">           </div>           <div class="form-group">             <label for="exampleinputemail1">email address</label>             <input type="email" class="form-control" id="email" placeholder="please enter password">           </div>                     <div class="form-group">             <label for="exampleinputpassword1">password</label>             <input type="password" class="form-control" id="password" placeholder="password">           </div>           <div class="form-group">             <label for="exampleinputpassword1">re-password</label>             <input type="password" class="form-control" id="re-password" placeholder="password">           </div>                     <button type="submit" class="btn btn-default">submit</button>         </form>        </div>       </div>      </div>     <script src="js/login.js"></script>     <script href="js/bootstrap.js"></script>     <!-- /.container -->   </body> 

why value not html <p> tag.

your code works. since function executes on submitting form, username gets logged in console fast before page refreshed submitted data. can confirm , test adding event.preventdefault(); function prevent submitting form page stay visible console.

<script>     var login = new function()     {     var name = null ;      this.validation = function()     {         event.preventdefault();         this.name = document.getelementbyid("username").value;         console.log(this.name);          document.getelementbyid("demo").innerhtml = this.name;         };     }; </script> 

if that's not you're looking for, let me know.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -