faqts : Computers : Programming : Languages : JavaScript : Forms : TextAreas/TextFields

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 8 people (50%) answered Yes
Recently 4 of 8 people (50%) answered Yes

Entry

How do I monitor content of a text field *while* a user is typing?

May 13th, 2002 06:40
Neil Hardie, Jean-Bernard Valentaten,


Have you tried using the onChange-handler??
Jean
------
Yes - but it's only triggered once the field loses focus.  I want to 
validate while the user is still typing in the field - this is to 
dynamically activate a "save" button, which is only available once this 
field has content.
------
Well, then I'm afraid you'll have to use setTimeout and check the 
content of the textfield on a regular basis:
var checkTimeout = null;
function checkText()
{
  if (document.myForm.myTextfield.value != '')
  {
    checkTimeout = null;
    activateSaveButton();
  }
  else
    checkTimeout = setTimeout('checkText()', 2000);
}
This will check the textfield every two seconds. If the content is not 
empty, then no further check is performed and the save button is 
activated, else the next check is performed in two seconds.
HTH,
Jean
----------------------------------------------------
Thanks Jean, good thinking! Here's what I finally used, in case it's 
useful to others - I need the field to be constantly monitored while it 
has focus.  Availability of the save button is indicated by changing 
its class.
var vCheckInterval = null;
var vSaveButtonStatus = false;
gSaveButtonEl = document.getElementById('saveButton');
function monitorField(myField) {
   if (event.type == 'focus') {
      vCurrentRequiredField = myField;
      vCheckInterval = setInterval('monitorFieldSniffer()', 100);
   }
   else
      vCheckInterval = null;
}
function monitorFieldSniffer() {
   if (vCurrentRequiredField.value != '') {
      if (!vSaveButtonStatus) {
         gSaveButtonEl.className='menu_save_button';
         vSaveButtonStatus = true;
      }
   }
   else if (vSaveButtonStatus) {
      gSaveButtonEl.className='menu_save_button_un';
      vSaveButtonStatus = false;
   }
}
<input onFocus="monitorField(this);" onBlur="monitorField(this);">