In the way below it will check if something was written using the regular expression /\w/
, which ignores the whitespace.
Edited example:
$("#buscar").on("blur", function(e) {
verify(e);
});
$("#buscar").on("keypress", function(e) {
if (e.keyCode == 13) {
verify(e);
}
});
function verify(e) {
if (!(/\w/.test($("#buscar").val()))) {
e.preventDefault();
$('p').html('Preencha algo!');
} else {
$('p').html('');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><formaction="">
<input type="text" id="buscar">
</form>
<p></p>
I used the blur () function that is triggered by the user to take the focus off of input
. But if you prefer click
, just put .on("click",
.