Javascript Select Input Event
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'); }
Solution 1:
You 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;
Solution 2:
If you use this way, the property name is onchange
:
filter.onchange = function() {
alert(this.value + "has been selected");
};
Further information:
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.
Solution 3:
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
Post a Comment for "Javascript Select Input Event"