Jquery If Value Is Greater Than a Certain Length

I'm trying to write some validation to check and see if a field is greater than a certain length and if it is throw an error. I can't seem to get it to work though and when I search for something normally take the .val() route to validate.

So I have

 $('.btn-danger').on('click', function(){
   if ($('input[name="spine_text"]').length > 22) {
     $('.spineError').html('This field must only have 22 characters.');
     $('.spineError').addClass('marginBottom');
     $('html, body').animate({
         scrollTop: ($('.cloth').first().offset().top)
     },500);
     $('.clothError').html('');
     return false;
   }

  });

and I have tried .length() > 22 as well. Neither of them work.

A jsFiddle to play with

1 Answer

You need to check the length of value of the input field, use .val() to get the value.

if ($('input[name="spine_text"]').val().length > 22) {

Demo: Fiddle

when you say $('input[name="spine_text"]').length it returns the number of input elements with name spine_text

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest