I'm trying to create a select input from javascript and bind a function to when a user changes an option. So far I have:
filter.change = function() {
console.log("CHANGED");
}
But nothing happens on selecting something else. What is wrong with this code. Also, how can I get the new selected value in the function ? Something like:
console.log(this.value + "has been selected")
I'm trying to create a select input from javascript and bind a function to when a user changes an option. So far I have:
filter.change = function() {
console.log("CHANGED");
}
But nothing happens on selecting something else. What is wrong with this code. Also, how can I get the new selected value in the function ? Something like:
console.log(this.value + "has been selected")
Share
Improve this question
edited Sep 22, 2014 at 10:57
mikemaccana
123k110 gold badges427 silver badges531 bronze badges
asked Aug 12, 2011 at 9:40
BogdanBogdan
8,2466 gold badges50 silver badges66 bronze badges
3 Answers
Reset to default 11You were close, you need to use onchange
:
filter.onchange = function() {
alert("CHANGED");
//You can alert the value of the selected option, using this:
alert(this.value + " was selected");
}
Of course as Delan said, you should addEventListener
(and attachEvent
) whenever possible. Example:
//Define a onchange handler:
var changeHandler = function() {
alert("CHANGED");
//You can alert the value of the selected option, using this:
alert(this.value + " was selected");
}
//First try using addEventListener, the standard method to add a event listener:
if(filter.addEventListener)
filter.addEventListener("change", changeHandler, false);
//If it doesn't exist, try attachEvent, the IE way:
else if(filter.attachEvent)
filter.attachEvent("onchange", changeHandler);
//Just use onchange if neither exist
else
filter.onchange = changeHandler;
If you use this way, the property name is onchange
:
filter.onchange = function() {
alert(this.value + "has been selected");
};
Further information:
- MDN - HTMLSelectElement
- quirksmode.org - Traditional event registration model
Note: There is also another way to register event handlers, which allows to assign multiple event handlers for the same event. For more information, have a look at quirksmode.org - Advanced event registration models.
if you would use jQuery, you can use it like this
$('select').change(function(){
alert($('select').val() + ' was just selected');
});
or use .onchange
filter.onchange = function() {
alert(this.value + " was selected");
}
instead of .change