Breandán
Breandán

Reputation: 1883

Javascript event that fires without user interaction?

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

Upvotes: 3

Views: 8267

Answers (7)

zmische
zmische

Reputation: 849

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

<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>

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:

 <input type='text' id='id_text_fld' value=''/>
    <select id='id_sel_one'>
     <option value="test1">Test1
     <option value="test2">Test2
    </select>
    <select id='id_sel_two'>
     <option value="test3">Test3
     <option value="test4">Test4
    </select>

Script for events:

<script>
    (function() {

        //create a new custom event, to be fired
        var onChangeValue = new YAHOO.util.CustomEvent("onChangeValue");
        // Attach change event listener for Select boxes by their IDs
      YAHOO.util.Event.on( ['id_sel_one', 'id_sel_two'], 'change', fnCallback, this);  
      // Function to call when Change event on Select occures
        fnCallback = function(e) { 
            alert("This elem:" + this.id+ " changed value to:" + this.value);
            // Fire our Custom event 
        onChangeValue.fire({dom_el: this}); // passing select box element [this] to function 
      }

      // Listen for Custom event and call our Func 
      onChangeValue.subscribe(fnSubscriberChange); // Lets listen for ChangeValue event and call our Func 
        fnSubscriberChange = function(type, args) {
             alert("Event type:" + type + " dom el id:" + args[0].dom_el.id );
             var dom_el = args[0].dom_el; // Select Box that produces Change
        };
    })();
    </script>

Upvotes: 0

Aron Rotteveel
Aron Rotteveel

Reputation: 83173

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 and createEvent functions. A simple demonstration of how you could implement this:

function triggerEvent(element, eventName)
{
    if (document.createEvent)
    {
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent(eventName, true, true);

        return element.dispatchEvent(evt);
    }

    if (element.fireEvent)
        return element.fireEvent('on' + eventName);
}

triggerEvent(document.getElementById('myTextbox', 'change'));

Using event.simululate.js, you would do it like this:

Event.simulate('myTextbox', 'change');

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.

Upvotes: 1

ciscoheat
ciscoheat

Reputation: 3947

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:

var textbox = document.getElementById("boxId");
textbox.value = "Abc";
textbox.onchange();

Of course, using a library like jQuery makes it easier and more robust:

$("#boxId").val("Abc").change();

Upvotes: 1

Ahmed Atia
Ahmed Atia

Reputation: 17960

Try to disconnect the logic responsible for changing the control's value from the onchange event's execution path using a setTimeout.

<html>
  <head>
    <script type="text/javascript">
      function setValue(target) {
        alert("changed - value: " + target.value);
        setTimeout("reallySetValue('" + target.id + "');", 1);
      }
      function reallySetValue(id) {
        var control = document.getElementById(id);
        control.value += control.value;
      }
    </script>
  </head>
  <body>
    <form>
      <div>
        Enter "a" here: 
        <input type="text" id="test" onchange="setValue(this)">  
        <br/>
        <br/>
        <input type="text">  
      </div>
    </form>
  </body>
</html>

It's illustrated here Changing a Textbox Value in its OnChange Event

Upvotes: 2

Gareth
Gareth

Reputation: 138042

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:

function updateTextField(new_text) {
  text_field.value = new_text;
  text_field.onchange();
}

Upvotes: 7

Kieron
Kieron

Reputation: 27107

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.

Upvotes: 2

heeen
heeen

Reputation: 4886

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()

Upvotes: 0

Related Questions