I’m making a very basic ‘contact us’ form, and I want to have a little “Thanks for your feedback” message appear on the page (not as an alert), upon successful form validation. The problem is, I hit the submit button, and the thankyou message appears for a split second and then disappears.
Code:
window.onload = init;
function init()
{
document.getElementById("contactForm").onsubmit=validate;
}
function validate()
{
//if statements to appear here returning false if any conditions are met
addMessage();
return true;
}
function addMessage()
{
var p = document.getElementById("content");
var l = document.createElement("p");
var m = document.createTextNode("Thanks for your message!");
l.appendChild(m);
p.appendChild(l);
}
What am I doing wrong? I am pretty new to javascript. Thanks!
You are returning
trueafter callingaddMessage(), so the message is displayed and then the form is submitted immediately.If you want to prevent immediate form submission, you can either use standard
alert()(it waits for user to press OK button) or prevent form submission by returning false and then submitting the form explicitly by callingform.submit()method when user clicks some button after he has read the message.Actually, message like “Thanks for your message!” should be displayed on target page specified in
actionattribute of the form and loaded after form is already sent. It’s not a good idea to say something that assumes the form is sent while it is not yet.