I tried for almost an hour to figure out how to perform some validation before submitting the form. My form is like this:
<!doctype html>
<head>
<title>sample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"> </script>
<script>
$("#myform").submit(function() {
alert("it is not working");
return false;
});
</script>
</head>
<body>
<form id="myform">
<input id="foo" value="Change me and press enter"/>
<input type="submit" />
</form>
</body>
</html>
It is not working in IE, Chrome FF 🙁
I must be doing something terribly wrong, but what?
EDIT
Working sample:
<!doctype html>
<head>
<title>sample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$("#myform").submit(function() {
alert("Now it is def working!");
return false;
});
});
</script>
</head>
<body>
<div id="myform">
<form id="myform">
<input id="foo" value="Change me and press enter"/>
<input type="submit" />
</form>
</div>
</body>
</html>
Wrap it in the ready function:
You need to wrap it in the ready function because where your function is now, the DOM element
#myFormdoes not exist, so you are attaching the handler to a non existent element.The ready function waits for the DOM to load and then runs everything inside of the ready fintion.