最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript select input event - Stack Overflow

programmeradmin5浏览0评论

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
Add a comment  | 

3 Answers 3

Reset to default 11

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;

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

发布评论

评论列表(0)

  1. 暂无评论