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?
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);
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With