0

I have a textbox whose width in pixel should be determined by the number of charaters in it. The font size for character is fixed.

My logic for this is to setg textbox's css-width to required width.

requiredWidth = "number of characters" * "fontsize in pixel" 

This simple formula Doesn't work. Any idea how to convert number of characters into pixels ?

Also is it possible to retrieve a dom element's size in pixel if the css.width is not set?

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
Mr. Zen
  • 704
  • 3
  • 7
  • 17
  • what is the `font-family`? the width depends on the character: an `i` is not the same as `M` in many families – greener Dec 13 '12 at 18:37
  • I know that the font size is useless for measuring. The problem is translating a group of characters (given font sizes) into pixels. – Mr. Zen Dec 13 '12 at 18:49

1 Answers1

2

Most fonts are not proportionally spaced. "WWWWW" is wider than "iiiii", therefore counting characters will not work.

You need to put the actual text in a SPAN in the DOM and measure its size.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • I know the first part. How do you propose to put the actual text in a span? Meaning create an span and destroy just to measure the size of the entire words? I have a bunch of controls , textareas/multiple select etc. whose css width has to be determined by looking at the number of characters contained. – Mr. Zen Dec 13 '12 at 18:47
  • 1
    http://stackoverflow.com/questions/2057682/determine-pixel-length-of-string-in-javascript-jquery – Iliya Reyzis Dec 13 '12 at 18:48
  • That's an ugly hack, not a proper solution at all. – Mr. Zen Dec 13 '12 at 18:55
  • No, that is the proper and ONLY way to get an accurate measurement. I could call it a "clever" hack, not an ugly one. – Diodeus - James MacFarlane Dec 13 '12 at 19:02
  • Sure. As I thought more about it, it does seem to be not too hard to actually inject a invisible span and nobody will ever notice:) Mitz ,Diodeus I take my comment back. – Mr. Zen Dec 13 '12 at 19:21