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...
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