Bogdan
Bogdan

Reputation: 8246

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");
}

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")

Upvotes: 2

Views: 20520

Answers (3)

genesis
genesis

Reputation: 50982

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

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 817198

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.

Upvotes: 5

Digital Plane
Digital Plane

Reputation: 38284

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;

Upvotes: 11

Related Questions