Reputation: 349
I am having issues with external javascript. Here is my basic form.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="../CSS/styles.css">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script src="../Javascript/UserScript.js" type="text/javascript"></script>
<title>Start Page</title>
</head>
<body>
<form id="newUser">
Email: <input type="text" name="Email"> <br/>
Password: <input type="password" name="Password"> <br/>
Confirm Password: <input type="password" name="ConfirmPassword"> <br/>
<input type="submit" name="Submit" />
</form>
</body>
If I call the following internally it works just fine. If I call it externally I get nothing.
$("#newUser").submit(function (event) {
event.preventDefault();
alert('hello world');
});
I even made a new file and did a test with something like this just to make sure jquery was working fine.
$(document).ready(function (e) {
alert('hello')
}
Upvotes: 0
Views: 30
Reputation: 101758
Put your code inside a document ready handler:
$(function () {
$("#newUser").submit(function (event) {
event.preventDefault();
alert('hello world');
});
});
You can't attach an event to an element before it exists. Your script runs before the #newUser
element has been parsed and added to the DOM. The $("#newUser")
in your code is producing an empty set.
Upvotes: 1