I have a input type text
<input type="text" id="txtid">
When i start typing text inside input, i should be able to get the lenght of the entered text.
This is what I tried:
document.getElementById("txtid").offsetWidth;
and
var test = document.getElementById("txtid");
var width = (test.clientWidth + 1) + "px";
These two does not give the width of the text entered
Basically what I want is:
For suppose input text
width is 320px
. I need the width of the entered text i.e 120px
, which keeps on changing when I enter.
Using the above solution, I turned it into a single function.
Canvas
measureText()
method can be helpful in such a case. Call the following function whenever you need to get your text width:For more accurate result, you may set font styling to the canvas, especially if you set some font properties to the input. Use the following function to get the input font:
Then, add this line to the frist function:
I see two ways.
First:
You can use a div with content editable instead input. Like this you can see the width of the div.
Note : Like @Leon Adler say, this way allows pasting images, tables and formatting from other programs. So you maybe need some validation with javascript to check the content before get the size.
Second:
Use an input type text and past the content into an invisible div. And you can see the width of the invisible div.
Note : For this way, you must have the same font and font size on
input
anddiv
tags.I have modified Chillers answer slightly, because it looks like you wanted the width rather than the letter count. I have created a span, which is absolute positioned off the screen. I am then adding the value of the input to it and then getting the width of the span. To make it more fancy you could create the span with javascript.
Note that the input and the span would have to have the same CSS styling for this to be accurate.
UPDATE
OLD
You can try this approach
Add a span and hide it
<span id="value"></span>
and then
onkeyup
add the text of thetextfield
on your hidden span and get its width.WITH THE HELP OF JQUERY
SNIPPET (UPDATED)
USING JS ONLY
SNIPPET (UPDATED)