DVCITIS
DVCITIS

Reputation: 1037

Javascript onchange event. select/option html dropdown input

var inputDrop = document.createElement('select');
inputDrop.setAttribute("onchange", function test(){alert("test");});
form.appendChild(inputDrop);


var inputOpt1 = document.createElement('option');
inputOpt1.value="1";
inputOpt1.innerHTML="1";
inputDrop.appendChild(inputOpt1);

var inputOpt2 = document.createElement('option');
inputOpt2.value="2";
inputOpt2.innerHTML="2";
inputDrop.appendChild(inputOpt2);

form.appendChild(inputDrop);

I need to assign somekind of event handler to select dropdown input field with a number of options. I need to execute a function whenever a different option is selected. The above doesnt work and neither does inputDrop.onchange="alert('test')"; not sure what im doing wrong here, please could someoneadvise?

thanks.

Upvotes: 2

Views: 21917

Answers (2)

pjdanfor
pjdanfor

Reputation: 346

Pete. What you're looking for is something like

inputDrop.addEventListener('change', function() {
    alert("PETE'S TEST"); });

I put together a jsFiddle to demonstrate this working: http://jsfiddle.net/pbaXP/1/

Upvotes: 6

Arun P Johny
Arun P Johny

Reputation: 388446

This seems to be working

inputDrop.onchange = function test(){alert("test");};

Working demo here

Upvotes: 0

Related Questions