3

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?

4 Answers 4

6

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't this always call test()? I want AN01 to call one function, AN02 to call another and AN03 to call another.
2

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

Comments

1

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

1 Comment

The drop down menu I have above is only part of it. I also have some values that are AR01A, GL04, etc. So I don't think this would work.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.