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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like