You have to catch the submit
event on the form. If the input is invalid, then prevent the default behavior.
$("form").on("submit", function () {
var isInvalid = false;
$("input", this).each(function () {
if (!$(this).val()) {
isInvalid = true;
}
});
if (isInvalid) {
return false;
}
});
If you only need to catch the blur event then, just do it!
$(document).ready(function() {
var $error = $(".alert-danger");
$("form input").on("blur", function() {
if (!$(this).val()) {
$error.removeClass("hide").text("No value");
} else {
$error.addClass("hide");
}
});
});
@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<form action="">
<input type="text" class="form-control" placeholder="Text input">
<div class="errors">
<div class="alert alert-danger hide"></div>
</div>
</form>
</div>