A textbox on my form may change depending on what's selected in various drop down lists.
Is there a way to call a javascript function when the textbox value changes?
Tried onchange event but this only seems to work if a user manually changes the textbox value.
Cheers,
Breandán
You can use the excellent event.simulate.js to do this. This script does depend on the Prototype.js library, though.
If you'd want to this without relying on an external library, take a look at the
fireEvent
andcreateEvent
functions. A simple demonstration of how you could implement this:Using event.simululate.js, you would do it like this:
A similiar question was asked here: Trigger an event with Prototype.
EDIT: although it is possible to use
document.getElementById('myTextbox').change()
, I would not recommend doing it, as it makes your code less flexible. When attaching onChange events to the textbox, these would not trigger when manually calling the change() event. Using the above method, events will propagate, just as if the event was a user-triggered one.I'd recommend to look over YUI's Custom events for Example: YUI Custom Event Example Link
All you need is to attach this script with Events manipulations
and then you are able to use Custom Events (everywhere in HTML) fnSubscriberChange - inside this Func you could do whatever you want. You could put your textbox change value logic here and depend on the Changed Select box value - call desired func. Logic that depends on Event listening is clear and easy to modify; YUI library supports all browsers so you shouldnt mind about browsers features.
Text box and select boxes:
Script for events:
In web browsers, programmatic changes on a control won't trigger events on that control. You must instruct the code that changes the textbox value to trigger the onchange event. This is how you can do it in plain javascript:
Of course, using a library like jQuery makes it easier and more robust:
When setting the content of the text box from your JS code, call out to another function passing in the text to set, you can then call it from where ever you need and do your logic then.
Assuming the frontend is in html:
You could install a timout callback and query the contents of the textbox in intervals of, say, 100msecs and compare it to some previous value you store in a variable.
Keywords: window.setTimout(), window.setInterval()
No, javascript-triggered changes to form elements don't trigger events. If they did, this would cause all sorts of recursive infinite loops.
The simple solution is to call your onchange function manually whenever you change the value of the textbox, however you could also use some kind of wrapper function. As a very basic example: