Forum Moderators: open
<input id="example1" name="example1" onblur="setstylebyid('example1','width','200px');" onkeypress="my_function1('example1');" value="" />
// i = id of the element
// p = CSS property (e.g. font-size)
// v = value (e.g. '20px')
function setstylebyid(i,p,v)
{
if (document.getElementById(i))
{
var n = document.getElementById(i);
if (n != null) {n.style[p] = v;}
}
else {alert('Error: the id \''+i+'\' was not found or has not yet been imported to the DOM.\n\nNew property intended: '+p+'\n\nNew value intended: '+v);
}
function my_function1(id)
{
var l = document.getElementById(id).value.length;
var w1 = 10; //width per character
var w2 = l*w1; //characters times character width
var new_width = 200+w2 // minimum width plus typed width
if (new_width>500) {new_width = 500;} // prevent width over 500
setstylebyid('example1','width',new_width+'px');
}
<!DOCTYPE html>
<html>
<head>
<title>JS Test TextBox</title>
<script type="text/javascript">
function textexpand(id, minwidth, maxwidth, chartoexpand)
{
var item = document.getElementById(id);
var l = document.getElementById(id).value.length;
if (l > chartoexpand) //only start after we've hit the point where it should expand
{
var w2 = ((l-chartoexpand) * 10) + minwidth;
var new_width = w2; // minimum width plus typed width
if (new_width>maxwidth) {new_width = maxwidth;} // prevent width over maxwidth
item.style['width'] = new_width+'px';
}
}
</script>
</head>
<body>
<input id="example1" name="example1" onkeypress="textexpand('example1', 200, 500, 20);" value="" style="width:200px;" />
</body>
</html>