2

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();

    });
});
Joren
  • 3,068
  • 25
  • 44
KB9
  • 599
  • 2
  • 7
  • 16

4 Answers4

5

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;
}
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
2

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:

  • anywhere after the name element
  • in a script block with the defer attribute
  • in a window.onload handler
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

I think your function always returns false. Try,

function valid_name() {
        if (($("#name").val().length > 5) && ($("#name").val().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();

            });
        });

.val() gives the value of input field, and you should be checking value's length.

$('#name').length would return count of elements with id name, that is surely less than 5.

Optimus Prime
  • 6,817
  • 5
  • 32
  • 60
1

You spelled the div id as "name_erors", which seems like a misspelling. I would double check the spelling in the html first.

jtoomey
  • 114
  • 3