set onchange event in webblock

set onchange event in webblock

I created a webblock, which holds a javascript function that is called on the onload of the screan..
This method is supposed to set the onchange event of all the mandatory input fields of  a form.
The problem is: it doens't work.. The method is called, but the onchange is not set.

Does anyone know what i did wrong? 

This is the webblock's javascript, which is called form the onload of the screen.. :

function getMandatoryFields(){
var mandatoryFields = document.getElementsByClassName('Mandatory');
alert("mandatory fields: " + mandatoryFields.length);
for(var i=0;i<mandatoryFields.length;i++){
mandatoryFields[i].onchange = "setMandatoryStyle()";
function setMandatoryStyle( ){

I know that the first function is called, for the alert "mandatory fields" shows... but, the onchange is not set (the alert "onchange" doesnot show).. 

Hi Martha,

You can modify your function to add the event inline (e.g. mandatoryFields[i].onchange = function(){dosomething...};)
A better option, to ensure you are adding a new event and not replacing an existing one, would be to use some helper code like the one on

Tiago Simões

thank you very much Tiago,
your advice is of great help!!
tried it out and it worked immediately! :-)
will look at John Resig's solution now, looks like a better plan!