onChange event doesn't trigger

Mayer M picture Mayer M · Jun 8, 2012 · Viewed 38k times · Source

I use Internet Explorer 8 and Sharepoint 2007.

Briefing: I have a NewForm with various fields from a list. I need, using javascript, from one of the fields, to get the value introduced by the user (in a textBox) and paste it on other field (other textBox) in the same page, using onChange.

Problem: I'm a JavaScript newbie, and I can't set the event 'onChange' to trigger my function, or at least to trigger an 'alert("Test") ... or simply I'm doing it wrong and don't know why (more likely)...

Let's assume the field I want to work with has as FieldName="IDTeam", type="text" and id="id_TeamField".

//My JS below "PlaceHolderMain"

_spBodyOnLoadFunctionNames.push("setTxtBoxesValues");

function setTxtBoxesValues()
{    
   //snipped

   getField('text','IDTeam').onChange = function(){alert('Test')}; 
   //"getField('text', 'IDTeam).onChange = function(){myFunction()};" 
   //If I want to call myFunction() when onChange event is triggered    
    }

Also, instead of getField, tried this:

document.getElementById('id_TeamField').onChange = function(){alert('Test')};

If I want to call myFunction() when onChange event is triggered

Any idea of what I'm doing wrong?

Answer

NSF picture NSF · Jun 8, 2012

onchange is an event so either you put it in the tag like this:

<input type="text" id="IDTeam" onchange="(call function here)" />

or you apply addEventListener to that DOM object:

document.getElementById("IDTeam").addEventListener("change", function() {//call function here});

in IE6 you may need: (not sure if it works as few people are using ie6 nowadays)

document.getElementById("IDTeam").attachEvent("onchange", function() {//call function here} )