Resizing Form Fields with JavaScript
Some web sites can benefit from a touch of "Wow"; something
fun to catch the visitor's attention.
The article shows how to change the size of type="text"
form fields. It also shows how to change the number of
rows to textarea fields. Adding columns (extending the
width) can be done just as easily.
The working example extends the type="text" form field
whenever the number of characters is near the size of the
field. And it adds a row to the textarea field whenever
the number of characters indicates it's time to do so.
It's done with JavaScript.
Two things need to be known before resizing a form field
can be accomplished: The name of the form and the name of
the form field.
Assuming the form's name is "FormName" and the field's name
is "FieldName," here are the JavaScript commands to use.
For type="text" form fields, the size attribute can be
changed:
document.FormName.FieldName.size = 33;
(assuming a new form field size of size="33")
For textarea form fields, both the cols and rows attributes
can be changed:
document.FormName.FieldName.cols = 40;
document.FormName.FieldName.rows = 7;
(assuming a new textarea size of cols="40" and rows="7")
The working example has a type="text" for a name and a
textarea field for a message.
When characters are typed into the name field, the size of
the field gets larger when the number of characters typed
is within 3 of the current size.
The rows of the textarea field increase when the number of
characters exceeds the number of characters per column
multiplied by the number of rows minus one.
You may wish to put this example into a web page just to
play with it. Watching the fields change size as you type
along can be entertaining.
Here is the form:
And here is the JavaScript.
The JavaScript can be put anywhere on the page, above or
below the form or even in the HEAD area of the source code.
Fun can be had with this idea.
Your site vistors likely will find this feature a little
surprising. Imagine the grin flashing across their face.
The idea can also be used in serious applications.
The above code comes from a JavaScript program I'm writing
that accepts text in a textarea field, processes it, and
returns the changed text in the same textarea field. Because
the changed text is almost always different in size than the
original, I thought it would be nice to alter the field
accordingly.
Sometimes it takes so little to give something a bit more
elegance. Or, some surprises.
Question:
Did you find this article interesting and understandable? How can it be improved?
Your response is anonymous.
When done typing, click anywhere outside the box. [more info]
Will Bontrager
©Copyright 2006 Bontrager Connection, LLC Bontrager Connection, LLC
Please note:
Articles on this website are presented "as is". However -
If you have a question about a CGI script, HTML, CSS, PHP, or JavaScript
Ask one of our Experts and you'll have your answer!
Click here for details.