Is there a way to execute a javascript function when the user clicks on a certain <option> within a <select> drop down menu?
Asked
Active
Viewed 1.9k times
0
-
Possible duplicate of [Click on option event](https://stackoverflow.com/questions/4670405/click-on-option-event) – Mohammad Oct 31 '18 at 09:41
7 Answers
2
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.
Lil' Bits
- 898
- 2
- 9
- 23
2
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/
Šime Vidas
- 173,790
- 60
- 275
- 374
1
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
}
});
xbonez
- 40,730
- 48
- 157
- 236
-
seems like when someone does not specifically ask for a JQuery answer that it is kinder to answer in general javascript. Course I only say that cause I'm not what you'd call a jquery kind of guy. – Claude Apr 03 '12 at 23:29
-
1I do realize that, and I used to be a non-Jquery guy as well. But its been a while since I've been using Jquery, and quite honestly, I wouldn't know how to do this in vanilla JS anymore. – xbonez Apr 03 '12 at 23:30
0
You need to hook the onchange event of the <select> element, and check the value. Have you tried that?
uotonyh
- 778
- 6
- 6
0
Inside your <option> you could use the onclick event to specify a javascript function to be executed.
E.g.
<option onclick="yourFunction()">
FrogInABox
- 1,014
- 1
- 8
- 8
0
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!...
Shahrukh
- 1,356
- 4
- 15
- 20