My JavaScript form validation function is called two times

Home / Uncategorized / My JavaScript form validation function is called two times

Question:
I am trying to print the value from the form when a user submits the function but a blank value is returned.

Here is my 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 my HTML form as :

Login with javascript

Please Enter Following Details









Why does the value not get into html

tag.


Answer:
Your code simply works. But since the function executes on submitting the form, the username gets logged in the console fast before the page refreshed with submitted data. You can confirm this and test it by adding event.preventDefault(); to the function to prevent submitting the form so the page would stay visible with the console.

If that’s not what you’re looking for, let me know.
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *