19

I have this:

function FilterSelect(select, search) {
    this.select = select;
    this.search = search;
    // Get the current list options
    this.options = this.select.options;
    // Whenever the text of the search box changes, do this
    this.search.onkeyup = function() {
        // Clear the list
        while(this.select.options.length > 0) {
            this.select.remove(0);
        }
    }
}

Inside of the onkeyup function I would like to access select, but I know it is not possible as is. What is the proper way to do this?

1
  • 1
    Try adding this.search.select = this.select as the third line of your function. Commented Aug 25, 2011 at 17:58

2 Answers 2

17

Before the onkeyup function, declare a variable. Something like var _this = this and then in the keyup function, just use _this instead of this.

So your code will look something like:

var _this = this;
// Whenever the text of the search box changes, do this
this.search.onkeyup = function() {
    // Clear the list
    while(_this.select.options.length > 0) {
        _this.select.remove(0);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

You need to create a variable which will be held in the closure scope of the onkeyup function:

function FilterSelect(select, search) {
    var _this = this;  // <-- win
    _this.select = select;
    _this.search = search;

    // Get the current list options
    _this.options = this.select.options;

    // Whenever the text of the search box changes, do this
    _this.search.onkeyup = function() {
        // Clear the list
        while(this.select.options.length > 0) {
            _this.select.remove(0);
        }
    }
}

By doing this, you ensure that the proper value will be referenced regardless of what scope the onkeyup function is called with (usually the global/window scope because of eventing).

EDIT
Actually, if you just need to access select, you should be able to do this already:

this.search.onkeyup = function() {
     // Clear the list
     while(this.select.options.length > 0) {
         select.remove(0);
     }
}

Comments

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.