Archive for the ‘Web development’ Category

How to dynamically update a form using javascript

Thursday, July 26th, 2007

This 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:

  1. function UpdateSize()
  2. {
  3. this.form.counter.value = 60 - this.form.comment.value.length;
  4. }
  5. 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:

  1. <form method="post" name="form">   Write your text here:
  2.  
  3. <textarea onkeydown="UpdateSize();" onfocus="UpdateSize();" rows="9" cols="45" name="comment"></textarea>
  4.  
  5.  
  6. Characters left: <input size="5" value="60" type="text" name="counter" />
  7. </form>

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:

  1.  <script type="text/javascript">
  2.  
  3. function UpdateSize()
  4.  {
  5.  this.form.counter.value = 60 - this.form.comment.value.length;
  6.  }
  7.  document.onkeydown=UpdateSize;
  8.  
  9. </script>
  10.  </head>
  11.  
  12. <form name="form" method="post" >
  13.  Write your text here:<br />
  14.  <textarea name="comment" cols="45" rows="9" onfocus="UpdateSize();" onkeydown="UpdateSize();" ></textarea>
  15.  <br />
  16.  Characters left: <input name="counter" type="text" value="60" size="5" />
  17.  </form>
  18.  </body>
  19.  </html>