Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input field value's length

Tags:

html

jquery

input

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.

like image 399
eomeroff Avatar asked May 08 '13 12:05

eomeroff


People also ask

How do you change input value length in HTML?

Input value length You can specify a minimum length (in characters) for the entered value using the minlength attribute; similarly, use maxlength to set the maximum length of the entered value, in characters. The example below requires that the entered value be 4–8 characters in length.

How do I limit the number of characters in an input field?

To set the maximum character limit in input field, we use <input> maxlength attribute. This attribute is used to specify the maximum number of characters enters into the <input> element. To set the minimum character limit in input field, we use <input> minlength attribute.

What is input field value?

The value attribute specifies the value of an <input> element. The value attribute is used differently for different input types: For "button", "reset", and "submit" - it defines the text on the button.

What is the minimum length a text field can be?

You can't set a minimum length on a text field. Otherwise, users wouldn't be able to type in the first five characters. Your best bet is to validate the input when the form is submitted to ensure that the length is six.


1 Answers

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);
      }
});
like image 58
Gautam3164 Avatar answered Sep 20 '22 15:09

Gautam3164