To follow unobtrusive JavaScript programming conventions, and depending on how quickly the DOM will load, it may be a good idea to use the following:
<form onsubmit="return false;"></form>
Then wire up events using the onload or DOM ready if you're using a library.
$(function() {_x000D_
var $form = $('#my-form');_x000D_
$form.removeAttr('onsubmit');_x000D_
$form.submit(function(ev) {_x000D_
// quick validation example..._x000D_
$form.children('input[type="text"]').each(function(){_x000D_
if($(this).val().length == 0) {_x000D_
alert('You are missing a field');_x000D_
ev.preventDefault();_x000D_
}_x000D_
});_x000D_
});_x000D_
});
_x000D_
label {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#my-form > input[type="text"] {_x000D_
background: cyan;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="my-form" action="http://google.com" method="GET" onsubmit="return false;">_x000D_
<label>Your first name</label>_x000D_
<input type="text" name="first-name"/>_x000D_
<label>Your last name</label>_x000D_
<input type="text" name="last-name" /> <br />_x000D_
<input type="submit" />_x000D_
</form>
_x000D_
Also, I would always use the action
attribute as some people may have some plugin like NoScript running which would then break the validation. If you're using the action attribute, at the very least your user will get redirected by the server based on the backend validation. If you're using something like window.location
, on the other hand, things will be bad.