I'm just doing some simple JavaScript homework but I can't figure out why my function isn't being called.
All I'm having te function do is alert("test") at the moment because I have to make sure the function is called before I actually write what it does. The JS file DOMassignment_3_ext.js resides in the same folder as the HTML file.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DOM Assignment: #3</title>
<script src="DOMassignment_3_ext.js">
</script>
</head>
<body>
<h2>Christmas Mad Libs</h2>
<form name="words">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Body-part</td>
<td><input type="text" name="body"></td>
</tr>
<tr>
<td>Animal</td>
<td><input type="text" name="animal"></td>
</tr>
</table>
<input type="button" onlick="madlibs(name, body, animal)" value="Submit">
</form>
<p>
<b class="name"></b> the Red-<b class="body"></b> <b class="animal"></b><br>
Had a very shiny <b class="body"></b><br>
And if you ever saw it<br>
You would even say it glows<br>
And all of the other <b class="animal"></b><br>
Used to laugh and call him names<br>
They never let poor <b class="name"></b><br>
Join in any <b class="animal"></b> games<br>
</p>
</body>
</html>
JS:
function madlibs(name, body, animal){
alert("test");
}
2 Answers 2
<input type="button" onlick="madlibs(name, body, animal)" value="Submit">
Should be:
<input type="button" onclick="madlibs(name, body, animal)" value="Submit">
2 Comments
The problem is that you are passing variables that don't exist! name does (there will always be a global variable name, but body and animal do not. Therefore, when you invoke the function as so:
onlick="madlibs(name, body, animal)"
onclick="madlibs(name, body, animal)" // and even when you spell it correctly
Javascript will say "body? I don't know anything called body!" It will then throw an error (a ReferenceError to be precise) and stop running the code. This means madlibs will not be called.
Until such a time as you have defined these variables, you can simply leave them out of the call:
onclick="madlibs()"
(In reality, it would be better to learn how to attach event handlers with Javascript, but that's a different story.)
Looking again, it's possible that these variables are defined in DOMassignment_3_ext.js, but it seems unlikely, given the name of the file...
<input type="button" onlick="madlibs(name, body, animal)" value="Submit">should be<input type="button" onclick="madlibs(name, body, animal)" value="Submit">. Typo is inonclickattribute nameonclickattribute is misspelled on your input.onlick... go ahead and start licking your computer.