I need to validate input using JavaScript and jQuery when someone submit my newsletter form
for some reason it does not work. it submit the form without alerting any errors
Here's what i have so far:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function go() {
if($('#name').val() == '') {
alert('error: name is required');
}
$('form').submit();
}
});
</script>
</head>
<form method="post" action="">
Name *<input type="text" name="name" id="name"/>
E-Mail *<input type="text" name="email" id="email"/>
<input class="submit" type="submit" value="Submit" name="submit" id="submit" onclick="go();">
</form>
Why I don't see the alert when I don't put anything in the name and then submit the form?
Rather than using onclick
on the submit button, use onsubmit="return go();
on the form element. Or, use jQuery $('form').submit(function(){ ... });
And, once you encounter an error, you need to return false
from the function to prevent it from executing any further.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With