Can anyone tell me why I keep getting a “displaymessage is not defined” error message with this code.. Thanks in advance 🙂
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TEST PAGE</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
function displaymessage() {
alert("Hello World!");
}
});
</script>
</head>
<body>
<p><input type="button" name="start" id="start" value="start" onclick="displaymessage()" /></p>
</body>
</html>
You define your
displayMessagefunction in a DOM Ready callback – which means that it will be defined when …well… the DOM is ready. And yet – you add it as a handler to a click of a DOM element – something that will be processed before the function is actually defined.Move the definition out of
$(document).ready(function(){...}and you’ll be OK.Additionally, the preferred way of binding handlers to various DOM events is programmatic, rather than declarative. Instead of adding an
onclickattribute to your button you should rewrite the entire thing to something like: