2

I am trying to dynamically add an on change event to an HTML select object. I can't seem to get it to work. I need the function to call dropDownChange and pass two parameters, this and nextDepth.

   var nextDepth = (int)......
   var selectBox = ......
   selectBox.onchange += function(nextDepth){dropDownChange(this, nextDepth);}; 

Not really sure how to tackle this... I figured this could would work. Any help you be GREATLY appreciated.

Thanks!

1
  • 3
    Could you post your html and real JavaScript? The ellipses don't help me understand what you're trying to do, or worth with... =/ Commented Jun 11, 2011 at 20:38

2 Answers 2

1
function changeonchange(){
    var selectBox = document.getElementById("selectBox");
    var nextDepth = getIntFromSomeWhere();

    selectBox.onchange = function() {
        var targ;
        if (!e) var e = window.event;
        if (e.target) targ = e.target;
        else if (e.srcElement) targ = e.srcElement;
        if (targ.nodeType == 3) // defeat Safari bug
            targ = targ.parentNode;
        dropDownChange(targ, nextDepth);
    };
}

You can get more info about events from http://www.quirksmode.org/js/events_properties.html every time "changeonchange" is called a new scope is created to hold the local variables and that scope is carried along the new onchange handler.

Sign up to request clarification or add additional context in comments.

1 Comment

Prusse, The variable nextDepth is an integer declared locally in the function that will be changing the select box's on change event.
1

I am assuming that you are looking for a way to pass in this in relation to the current executing object or namespace. To express this, the code example below uses an anonymous function, where this is stored to the variable me. Then when the select's change event triggers, your custom function is called, passing in the two specified variables.

(function() {
    var me = this;
    var selectBox = document.getElementById("selectBox");
    var nextDepth = 2;

    selectBox.onchange = function() {
        dropDownChange(me, nextDepth);
    };
})();

5 Comments

Greg thanks for the response, I was actually looking to pass this as a pointer to the select box itself.
@Dave: Passing a function pointer to a DOM object sounds ... well ... it doesn't make sense to me.
I mean this as in an instace of the select box. When it calls dropDownChange it will pass both a pointer to itself and the integer value of nextDepth
The this keyword will point to the selectBox DOMElement inside the onchange function.
It should have been just dropDownChange.call(this, nextDepth);. There's no need pass context as an argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.