Javascript – Problem with Change Event


Last week I encountered a problem in Internet Explorer (Déjà vu).
The functionality we needed was very simple to implement:
Check if the form was changed. That is, if the User is on the page and decides to just go out and form has changed, we needed to alert him.
What I thought then was to use the event change of the <form>.

I did the test in Firefox and everything went as planned. By changing the value of any element within the form the change event is fired.
But… in our “friend” Internet Explorer?
Surprise!
It did not work. So I went searching to see why the problem.
In this link  http://www.quirksmode.org/dom/events/change.html of QuirksMode is quite easy to understand.
In Internet Explorer the change event is not fired when the form is changed.

Note: Realize that it is only in IE it happens. Below is a list of browsers that support the change event in the form:

FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7
Font: QuirksMode.

Another Note: In IE the change event is not fired in the window and document objects. In all the above list does.
For Internet Explorer the only element that triggers the change event properly is the <input>.

Solution:
As the project was using jQuery was simple to solve another problem in IE. Follow the code below:


$(&quot;form *&quot;).bind(&quot;change&quot;, function(){ /* Code here*/});

The above code loops over all elements of form and atach the change event for each of them.

Well, that’s it.
Working and learning.

FF 2.0 FF 3.0 FF 3.1b2 Saf 3.0 Win Saf 3.1 Win iPhone 3G Chrome 1.0 Opera 9.62 Opera 10a Konqueror 3.5.7

Related Posts:

subscribe RSS feed!

, ,

  1. #1 by Carlso Ernica at October 16th, 2009

    Ola, poderia disponibilizar o código completo dessa validação?

    obrigado

  2. #2 by jaydson at October 16th, 2009

    Olá Carlso, segue abaixo um exemplo:

    var formChanged=false;

    $(“form *”).bind(“change”, function(){
    formChanged = true;
    });

    Simples assim.
    Desta maneira quando algum elemento do for alterado a variável formChanged terá o valor true.
    Basta agora na sua aplicação definir o que fazer com essa variável.
    No meu caso o que fiz foi no evento onbeforeunload verificar se a variavel era true. Tipo isso:
    window.onbeforeunload = function(){
    if(formChanged){
    return “O formulário foi alterado, tem certeza que deseja sair desta página?”
    }
    }

    Qualquer dúvida poste aqui.

    Abraço.

  3. #3 by Dhuankles Castro at July 27th, 2010

    massa o exemplo.. esse ie a cada dia tem passado mais raiva em desenvolvedores.. é um saco..

(will not be published)
  1. No trackbacks yet.
Free the web