Is there a way to execute a javascript function when the user clicks on a certain <option>
within a <select>
drop down menu?
<select>
elements support the onchange
event.
You can use the change
event to check which option the user clicked on and then execute your desired code.
In Jquery:
$('#yourSelect').change(function(){
var item = $(this).val();
if (item === "Specified Choice")
{
//do your stuff here
}
});
You HTML would look like this:
<select onchange="functionName(this.value)">
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
</select>
In your JavaScript, you would have a function ( ex: functionName()
)
and you would use that function to test for each case.
Here:
elem.onclick = function ( e ) {
if ( e.target.tagName.toLowerCase() === 'option' ) {
// an <option> element was clicked
// do your thing
}
};
where elem
is your SELECT element.
Live demo: http://jsfiddle.net/vBB7a/
You need to hook the onchange
event of the <select>
element, and check the value. Have you tried that?
Inside your <option>
you could use the onclick
event to specify a javascript function to be executed.
E.g.
<option onclick="yourFunction()">
Use Jquery in your Project..
HTML Code:
<select id="myselect">
<option value="">Select</option>
<option value="1">StactOverFlow</option>
<option value="2">SuperUser</option>
<option value="3">Another 1</option>
<option value="4">Another 2</option>
<option value="5">Another 3</option>
</select>
JQuery Code:
$("#myselect").bind('change', function(){
switch($(this).val()){
case "1":
click_action_1();
break;
case "2":
click_action_2();
break;
case "3":
click_action_3();
break;
}
});
function click_action_1(){
alert('Hi 1');
}
function click_action_2(){
alert('Hi 2');
}
function click_action_3(){
alert('Hi 3');
}
You can even execute a new javascript function with a <option>
Watch in Action: http://jsfiddle.net/extremerose71/PnfCk/8/
Enjoy!...