eomeroff
eomeroff

Reputation: 9915

Input field value's length

Is there a way with jQuery to find out the width of text inserted in input field of type text? I need that info because I need to perform some work when certain with is achieved. Also it would be very helpful for me to find the jQuery event that is occurring when user is entering one more character in input field which will make the first character of the whole value invisible?

Please see example http://jsfiddle.net/J58ht/2/

<input style="width: 35px;" type="text"> <span></span>


    $('input').on('keyup',function(){
      var input = $(this);
      input.next("span").text(input.val().length + " chars");
});

Try entering characters 123456 in the input field. When entering char 6 the first char 1 will be invisible.

I need that event, when value overlaps input.

Upvotes: 11

Views: 73722

Answers (8)

GautamD31
GautamD31

Reputation: 28763

You can find the length of the value by using jQuery's val() method which returns the current value of a form element as a string. Then you can use the length property from that string.

$('input').on('keyup',function(){
      alert('This length is ' + $(this).val().length);
});

Here's a working example on jsFiddle: http://jsfiddle.net/J58ht/

based on your edited question it should be like

$('input').on('keyup',function(){
      var my_txt = $(this).val();
      var len = my_txt.length;
      if(len > my_constant_length)
      {
          var res = my_txt.substring(1,my_constant_length);
          $(this).val(res);
      }
});

Upvotes: 15

Shijin TR
Shijin TR

Reputation: 7768

You can use length

    jQuery(selector).val().length;

Eg,

      $('#id').val().length;   
      $('#class name').val().length;   

Upvotes: 1

VenkateshKumar
VenkateshKumar

Reputation: 96

To find out the length of text you can use 

var len = $("#id").val().length;

$("#id").keyup(function(){
  var textLength = $(this).val().length;
  if(textLength > 15){
    alert('Length is exceeded');
    //Do ur stuff;
  }
});

Upvotes: 0

roger_that
roger_that

Reputation: 9791

var value = $("#textFieldId").val();
var fieldLength = value.length

This works.

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

you can try

  $("#target").val().length;

And remember length is not a function.

Upvotes: 0

Santosh
Santosh

Reputation: 12353

Try this

var inputLen = $("#txtInputText")[0].length

Upvotes: 0

PSR
PSR

Reputation: 40318

try this

$("#txtInputText").val().length

.length

Upvotes: 1

Freelancer
Freelancer

Reputation: 9074

Try to use:

var LengthOfText = $("#txtInputText").val().length;

Upvotes: 3

Related Questions