Vdas Dorls
Vdas Dorls

Reputation: 495

How to check input field's length?

How am I able to check input field's length?

For example, how to check if name entered in input field has length bigger than 2 characters?

Here is the code that I tried to use, but length always returns 0.

$(document).ready(function () {
     name = $("#name").val();
     $("#name").change(function () {
         if (name.length <= 2) {
             console.log(name.length);
             $("#name").addClass("error");
         } else if (name.length > 2) {
             $("#name").removeClass("error");
         }
     });
 });

Upvotes: 1

Views: 4968

Answers (1)

alex
alex

Reputation: 490183

Just put the name assignment inside of the change event.

 $(document).ready(function () {
     $("#name").change(function () {
         var name = $("#name").val();

         if (name.length <= 2) {
             console.log(name.length);
             $("#name").addClass("error");
         } else if (name.length > 2) {
             $("#name").removeClass("error");
         }

     });
 });

...or here is a different way of writing it...

$(function() {
    $('#name').change(function() {
        $(this).toggleClass('error', this.value.length <= 2);
    });
});

Upvotes: 3

Related Questions