I have this jQuery function I wrote up to set the size of an input based off of its data. In this case I have already figured out the widths for each character based off of a 12px font size for Helvetica.
It's not super flexible or anything, but I would like to know if there is any good way to take what I have and maybe make it more elegant (or fewer lines of code).
HTML:
<input value="Some really long string about nothing important"" />
CSS:
body {
font-family:Helvetica;
font-size:12px;
}
span {
padding:0;
margin:0;
}
input {
border:0;
}
JavaScript / jQuery:
// Helvetica, 12px or 1.2em at 62.5%
var str = $('input').val();
var length = str.length;
var charWidth = 0;
for ( var i = 0; i < length; i++ )
{
console.log(str[i]);
if ( str[i] == "f" ||
str[i] == "i" ||
str[i] == "I" ||
str[i] == "j" ||
str[i] == "l" ||
str[i] == "t"
)
{
charWidth += 3;
}
if ( str[i] == "r" )
{
charWidth += 4;
}
if ( str[i] == "v" ||
str[i] == "x" ||
str[i] == "y" ||
str[i] == "z"
)
{
charWidth += 5;
}
if ( str[i] == "c" ||
str[i] == "k" ||
str[i] == " "
)
{
charWidth += 6;
}
if ( str[i] == "a" ||
str[i] == "A" ||
str[i] == "b" ||
str[i] == "d" ||
str[i] == "e" ||
str[i] == "F" ||
str[i] == "g" ||
str[i] == "h" ||
str[i] == "J" ||
str[i] == "L" ||
str[i] == "n" ||
str[i] == "o" ||
str[i] == "p" ||
str[i] == "q" ||
str[i] == "s" ||
str[i] == "T" ||
str[i] == "u" ||
str[i] == "V" ||
str[i] == "X" ||
str[i] == "Y" ||
str[i] == "Z" ||
str[i] == "0" ||
str[i] == "1" ||
str[i] == "2" ||
str[i] == "3" ||
str[i] == "4" ||
str[i] == "5" ||
str[i] == "6" ||
str[i] == "7" ||
str[i] == "8" ||
str[i] == "9"
)
{
charWidth += 7;
}
if ( str[i] == "B" ||
str[i] == "E" ||
str[i] == "K" ||
str[i] == "P" ||
str[i] == "S"
)
{
charWidth += 8;
}
if ( str[i] == "C" ||
str[i] == "D" ||
str[i] == "G" ||
str[i] == "H" ||
str[i] == "M" ||
str[i] == "N" ||
str[i] == "O" ||
str[i] == "Q" ||
str[i] == "R" ||
str[i] == "U" ||
str[i] == "w"
)
{
charWidth += 9;
}
if ( str[i] == "m" || str == "W")
{
charWidth += 11;
}
}
$('input').css({'width': charWidth});
if/else
. You could also make this function a jQuery plugin so you could just so$('input').autoSize();
\$\endgroup\$