Live Updates from Text Input in JavaScript

It is quite common to update a Web page immediately and continuously in response to user input in a text box (i.e. an <input type=text> or a <textarea>). Common motivations would be to provide auto-completion or suggestion features, to validate the content of an HTML form, or to implement a live preview feature like the one used for comments on this very blog.

This is quite simple to do, but as it seems to be somewhat of a frequently asked question I decided to publish an answer.


Type in the text box to try it:



On keyboard or mouse events that might change the contents of the text box, we set a timeout. We don't want to have several timeouts running at the same time, so if there is one already running we cancel it. We set a timeout rather than just reading the value directly, since this would be inefficient, and doesn't work for events which fire before the value property in the DOM is updated.

When the timeout fires, we get the current value of the text box, do whatever we need to with it, and update the page.

  1. Jdan

    Fun :)

  2. Sam

    Works great. Operational limit: 524,287 characters ... any idea why it dies at 2^19? I guess it's probably 'count's data type.

    Pretty Cool stuff! I especially like the comments :)

    1. inimino

      Sam, I think the length limit is imposed by the browser as a limit on the length of a single <input type=text>. Had I used a <textarea> instead, this limit would probably be higher, and I'm sure this varies between browsers.

      In a recent Firefox build I got up to "You entered 2097152 characters." before stopping testing. (Hold down Ctrl and hit A C V V to double the length of the text.)