views:

286

answers:

2

Hi all.

I've got a hidden form field, and when a button gets pressed the value of the hidden field is changed. Now, I've added an observer to the hidden field, listening for changes to occur. For some reason, though, the event listener never kicks in, even though the value of the hidden element changes. I'm using Prototype and Firefox 3.6.

The code looks roughly like this:

button.observe('click', function(event) {
  hiddenField.setValue(someValue);
});

hiddenField.observe('change', function(event) {
  alert('It works!');
});

Does anyone have a clue why the latter observer doesn't execute?

Thanks!

A: 

I don't think input elements that are hidden respond to that event.

I don't know prototype, but I think the events being triggered is entirely up to the browser.

Here is an example with jQuery on JSbin. Notice that changing the text yourself fires the event, however the next part of code that changes the value via script does not fire it.

alex
Thanks alex. I tried changing the element to a normal text type field, just to see if it was the hidden type that did it, but the result was the same. Silly thing, really. Firing a custom event did the trick, though.
Johan Fredrik Varen
+1  A: 

You need event.simulate.js

Fire the event..

button.observe('click', function(event) {
  hiddenField.setValue(someValue);
  hiddenField.simulate('change');
});

And then observe it:

hiddenField.observe('change', function(event) {
  alert('It works!');
});
David Titarenco
I ought to thump myself for not thinking of that. Thanks a lot David. Since I use Prototype already, I simply used hiddenField.fire('custom:change'), and it all works like a charm :)
Johan Fredrik Varen
Yep, if firing non-native events is okay with you, you can just fire namespaced custom events like you showed :)
David Titarenco