One of the problems I am experiencing at the moment is not being able to call a function in the onclick
event of the submit button.
$(document).ready(function() {
function validate() {
var contactName = document.getElementById("contact-name").value;
alert("Thank you " + contactName);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="name">NAME</label>
<input id="contact-name" name="name" placeholder="Please enter your name..." type="text">
<label for="email">EMAIL</label>
<input id="contact-email" name="email" placeholder="Please enter your contact email..." type="text">
<label for="email">MESSAGE</label>
<textarea id="contact-message" name="message" placeholder="Please enter your message.."></textarea>
</form>
<button type="button" id="submit" onclick="validate();">SUBMIT MESSAGE</button>
As others have mentioned, the issue here is the scope that the
validate()
function is defined in.JavaScript is "lexically scoped", meaning that the location of a declaration determines from where it can be reached by other code.
Your
validate
function is declared (scoped to) inside the anonymousdocument.ready
function. This means that the only place wherevalidate
can be "seen" is by other code that shares that scope. Theonclick=validate()
line is outside of that scope and that is why your function isn't being called.However, instead of moving the
validate()
function outside of thedocument.ready()
callback (thus making it global, which is a bad thing), you really should remove theonclick
inline HTML event attribute as this is a bad practice (see this for several reasons why) and do the event binding in the script area. This approach will allow you to set up the event in the same scope as thevalidate()
function and keep the HTML clean:Here's a bit more on scope.
You should write the
validate()
function outside the$(document).ready
as theonclick
in binded when the DOM loads - while$(document).ready
scopes the function.This means the function is local to the closure and will not be visible globally if its written so inside
$(document).ready
.See demo below:
First, you should avoid inline handlers like that. Second, depending on the form submission process. You should have the button inside your
<form>
tags. Then add<form method="POST" action="/someurl/to/post/to">
.Otherwise, use jQuery and
$.ajax()
with aclick
event handler: