Eses
Eses

Reputation: 15

add onchange to <select>

I want to add an onchange function to my created select, but it didn't work. Does someone know how you add onchange to a select? This is my code:

   function maandgen(){

    var ma = document.createElement("select");
    ma.id='kies';
    ma.onchange='change';

Upvotes: 1

Views: 262

Answers (2)

A.B
A.B

Reputation: 20455

You need to assign a function to onchange property of newly created element. and Add that to document as well

function maandgen(){

    var ma = document.createElement("select");
    ma.id='kies';
    ma.onchange= changefunction; 
    document.appendChild(ma);

}

function changefunction(){

   alert("changed");

}

i want to use the value of my option in my function howe can i to that?

if you want to pass an argument or "this" to function you can do

replace

ma.onchange= changefunction; 

with

ma.setAttribute('onchange', 'changefunction(this)');

and now change function becomes

function changefunction(item) {
    var value = item.value;  
}

Upvotes: 2

Chilipote
Chilipote

Reputation: 1067

try this

function maandgen(){
    var ma = document.createElement("select");
    ma.id='kies';
    ma.onchange= function() {/* write your action here */};
};

Upvotes: 0

Related Questions