Carmen
Carmen

Reputation: 35

drop down menu with onclick javascript functions

I'm trying to create a drop down menu that calls a JavaScript function when clicked. My drop down menu is like this:

<select name = "navyOp"> 
    <option selected = "selected">Select a Navy Op Area</option>
    <option value = "AN01">AN01</option>
    <option value = "AN02">AN02</option>
    <option value = "AN03">AN03</option>
</select>

So for each of this options, I want a specific JavaScript function to be called. Is there a simple way to do this?

Upvotes: 3

Views: 44943

Answers (4)

Alex Char
Alex Char

Reputation: 33228

You can attach an event listener to select element:

window.test = function(e) {
  if (e.value === 'AN01') {
    console.log(e.value);
  } else if (e.value === 'AN02') {
    console.log(e.value);
  } else if (e.value === 'AN03') {
    console.log(e.value);
  }
}
<select name="navyOp" onchange="test(this);">
  <option selected="selected">Select a Navy Op Area</option>
  <option value="AN01">AN01</option>
  <option value="AN02">AN02</option>
  <option value="AN03">AN03</option>
</select>

Upvotes: 6

tks.tman
tks.tman

Reputation: 414

You can try this

html change or edit:

<select name = "navyOp" id = "navyOp"> 

JavaScript:

    document.getElementById("navyOp").onchange = function()
{

    if(this.value === "AN01")
    {
        //do this function
        alert("an01");
    }
    else if(this.value == "AN02")
    {
        //do this function
        alert("an02");
    }
    else if(this.value == "AN03")
    {
        alert("an03");
    }
};

Upvotes: 2

user3359953
user3359953

Reputation: 47

One way to do this is

function expand(s)
{
  var td = s;
  var d = td.getElementsByTagName("div").item(0);

  td.className = "menuHover";
  d.className = "menuHover";
}

You have to do this for each of your options menu. Hope this answers your question

Upvotes: 0

blex
blex

Reputation: 25659

You could add a function that gets called everytime you change the value :

HTML

<select name = "navyOp" onChange="myFunction()"> 
    <option selected = "selected">Select a Navy Op Area</option>
    <option value = "AN01">AN01</option>
    <option value = "AN02">AN02</option>
    <option value = "AN03">AN03</option>
</select>

JS

var myDropdown=document.getElementsByName('navyOp')[0];

function myFunction(){
    alert('option changed : '+myDropdown.value);
}

JS Fiddle

Upvotes: 1

Related Questions