Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - check length of input field?

Tags:

jquery

The code below is intended to enable the submit button once the user clicks in the textarea field. It works, but I'm trying to also make it so that it's only enabled if there's at least one character in the field. I tried wrapping it in:

if ($(this).val().length > 1)  {  } 

But, that didn't seem to work... Any ideas?

$("#fbss").focus(function () {     $(this).select();     if ($(this).val() == "Default text") {         $(this).val("");         $("input[id=fbss-submit]").removeClass();         $("input[id=fbss-submit]").attr('disabled', false);         $("input[id= fbss-submit]").attr('class', '.enableSubmit');         if ($('.charsRemaining')) {             $('.charsRemaining').remove();             $("textarea[id=fbss]").maxlength({                 maxCharacters: 190,                 status: true,                 statusClass: 'charsRemaining',                 statusText: 'characters left',                 notificationClass: 'notification',                 showAlert: false,                 alertText: 'You have exceeded the maximum amount of characters',                 slider: false             });          }     } }); 
like image 436
TwixxyKit Avatar asked Apr 24 '10 01:04

TwixxyKit


People also ask

How to get length of input in jQuery?

We can find the length of the string by the jQuery . length property. The length property contains the number of elements in the jQuery object. Thus it can be used to get or find out the number of characters in a string.

How do you find the length of an input?

In this tutorial, we are going to learn about how to get the length of an entered text in textbox using JavaScript and jQuery. To get the length of an input textbox, first we need to use access it inside the JavaScript by using the document. getElementById() method. const textbox = document.

What does .length do in jQuery?

The length property in jQuery is used to get the number of elements in the jQuery object.


2 Answers

That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if condition is always true.

The simplest way to make it work, it seems to me, is to account for this case:

    var value = $(this).val();     if ( value.length > 0 && value != "Default text" ) ... 
like image 191
Fyodor Soikin Avatar answered Oct 19 '22 18:10

Fyodor Soikin


If you mean that you want to enable the submit after the user has typed at least one character, then you need to attach a key event that will check it for you.

Something like:

$("#fbss").keypress(function() {     if($(this).val().length > 1) {          // Enable submit button     } else {          // Disable submit button     } }); 
like image 26
user113716 Avatar answered Oct 19 '22 18:10

user113716