Reputation: 9915
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
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
Reputation: 7768
You can use length
jQuery(selector).val().length;
Eg,
$('#id').val().length;
$('#class name').val().length;
Upvotes: 1
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
Reputation: 9791
var value = $("#textFieldId").val();
var fieldLength = value.length
This works.
Upvotes: 0
Reputation: 121998
you can try
$("#target").val().length;
And remember length
is not a function.
Upvotes: 0
Reputation: 9074
Try to use:
var LengthOfText = $("#txtInputText").val().length;
Upvotes: 3