onChange (Event handler)

Triggered when the value belonging to an input element is changed.


JavaScript - 1.0
JScript - 3.0
Internet Explorer - 4.0
Netscape - 2.0
Opera - 3.0
Property/method value type:Boolean primitive
JavaScript syntax:-myObject.onchange = aHandler
HTML syntax:<HTMLTag onChange="..."> <INPUT onChange="...">
Argument list:aHandlerA reference to a function object to handle the event
Supported by objects:BODY, CAPTION, Checkbox, DIV, FIELDSET, FileUpload, IMG, Input, LEGEND, Password, RadioButton, Select, TEXTAREA, TextCell

When the data in the input element is modified, the ONCHANGE event handler is called.

You can place some script code directly into this handler like this:

   <INPUT TYPE="TEXT" ONCHANGE="alert('Changed');">

In this context, you can refer to the input element itself using the 'this' keyword. Thus:

   <INPUT TYPE="TEXT" ONCHANGE="this.value=checkValue(this.value);">

This will check the value and reset it to an allowed value. That may be to force it to be all lower case for example or to remove weird characters.

Actually, you don't need to pass this.value because it's accessible from within the function. Functions inherit some scope according to how they are called so this would be better:

   <INPUT TYPE="TEXT" ONCHANGE="this.value=checkValue();">


   function checkValue(anObject)


   this.value = this.value + "XXX";

   return true;



This is also a particularly useful event to handle on behalf of a <SELECT>/<OPTION> control although it is not supported fully in all browsers.

Because the MSIE version 3.0 browser doesn't trigger this event, it has become popular to place a small input button beside the selector so the user can select and then trigger. If you do that, you really should make that technique browser-version sensitive and 'do the automatic thing' when you can.

See also:Event, Event handler, Event model, Event names, Event object, Event.returnValue, FileUpload object, Handler, Password object, Select object, Semantic event, TEXTAREA object, TextCell object


Wrox Instant JavaScript - page - 53