How to dynamically update a form using javascript
Thursday, July 26th, 2007This article shows you how you can display a box with “characters left” in your forms, you may for example use it in guestbooks or comment forms to tell the user how many characters he/she are allowed to input.
Since this is done by javascript, all we need is a .html file, with the script, and the form.
This is how the javascript looks like:
-
function UpdateSize()
-
{
-
this.form.counter.value = 60 - this.form.comment.value.length;
-
}
-
document.onkeydown=UpdateSize;
It changes the textbox “lengde”s value to 60 minus the length of the typed text in the big textarea called “txt”. It updates every time you release a key on the keyboard.
The html form looks like this:
That is the form called “form”, with the textarea called “txt” and the update box with the counter called “display_counter” .
If you put the javascript in the head tag and the form in the body tag, it would look like this:
-
<script type="text/javascript">
-
-
function UpdateSize()
-
{
-
this.form.counter.value = 60 - this.form.comment.value.length;
-
}
-
document.onkeydown=UpdateSize;
-
-
</script>
-
</head>
-
-
<form name="form" method="post" >
-
Write your text here:<br />
-
<textarea name="comment" cols="45" rows="9" onfocus="UpdateSize();" onkeydown="UpdateSize();" ></textarea>
-
<br />
-
Characters left: <input name="counter" type="text" value="60" size="5" />
-
</form>
-
</body>
-
</html>
