I have this code to display an error when function valid_name is not true and to hide the error when the valid_name become true when blur;
Error is display in a div which is initially hidden.
The error appears but it doesn't disappear.
function valid_name() {
if (($("#name").length > 5) && ($("#name").length < 20)) {
return true;
} else {
return false;
}
}
$(document).ready(function() {
$('#name').on('blur', function() {
if (!valid_name())
$("#name_erors").text("invalid name").show();
if (valid_name())
$("#name_erors").hide();
});
});
I think
$("#name").length
should
$("#name").val().length
Cause $('#name').length count the element found, but to count the character within you need to use
$("#name").val().length
So function should be
function valid_name() {
if (($("#name").val().length > 5) && ($("#name").val().length < 20)) {
return true;
} else {
return false;
}
}
You can also do
function valid_name() {
var value = $('#name').val(), len = value.length;
return len > 5 && len < 40;
}
When selecting with jQuery, the returned object contains elements. In this case, there'll only be one, so the length will always be 1. You probably meant to select the length of the value.
That said, here's a fully optimised Vanilla JS solution:
document.getElementById('name').onblur = function() {
var notice = document.getElementById('name_errors');
if( this.value.length > 5 && this.value.length < 20) notice.style.display = "none";
else {
notice.style.display = "block"; // or "inline", as applicable
notice.innerHTML = "Invalid name length (must be between 6 and 19 characters)";
}
};
This code should be placed either:
name elementdefer attributewindow.onload handlerIf 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