0

I have the next menu in HTML:

<select name="p1">
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>

Now, I want to send it to my JS function:

function myFunc(menuValue){
//do something
}

How can I do it?

0

3 Answers 3

2

Something like this :

Javascript :

var selectObj = document.querySelector("#selectID"),
    displayObj = document.querySelector(".display");
selectObj.onchange = function(evt){
    myFunc(this.value);
}

function myFunc(menuValue){
    displayObj.innerHTML = menuValue; 
}

HTML :

<select id = "selectID" name="p1">
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>
<div class='display'></div>

http://jsfiddle.net/NeekGerd/4H5aq/

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

2 Comments

Why are you using querySelector to select by Id? Also display may as well be an id rather than a class.
Bad habit. I'm using jQuery too much I guess.
1

So you want to get the value of the selected option onchange of option value right? You can try this way:-

http://jsfiddle.net/T8CKU/

<select name="p1" onchange="myfunc(this.value);">
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>

function myFunc(menuValue){
    alert(menuValue)
}

Here inside myFunc the context of `this would be the window. If you want to get the context inside the window as the dropdown itself you can use apply or call.

<select name="p1" onchange="myFunc.call(this);">
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>

function myFunc(){
    alert(this.value); //This will give the value again.
}

Comments

0

The select element in HTML offers an onchange event that fires if you select a new value (new = an option that was not selected).

<select name="p1" onchange="myFunc(option);">
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>

function myFunc(option) {
  // whatever you need to do
};

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.