Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click on option event

Tags:

how do I handle events for option elements?

<select>       <option value='option1'>Gateway 1</option>       <option value='option2'>Gateway 2</option>       <option value='option3'>Gateway 3</option>  </select> 

When an option element is clicked I want to display a little description for the element. Any ideas how to do that?

like image 266
UpCat Avatar asked Jan 12 '11 15:01

UpCat


People also ask

How can set click event in select option?

$('#mySelect option'). bind('click', function(){ console. log('hi! '); });

What is the click event?

An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.

How do I trigger a click event without clicking?

If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.

How do I find the click event in my browser?

You can detect clicks inside the page with a simple click event handler: document. onclick= function(event) { // Compensate for IE<9's non-standard event model // if (event===undefined) event= window.


2 Answers

You're going to want to use jQuery's change event. I am displaying the text of your option as an alert, but you can display whatever you want based on your needs. (You can also, obviously, put it inside another part of the page...it doesn't need to be an alert.)

$('#myOptions').change(function() {     var val = $("#myOptions option:selected").text();     alert(val); }); 

Also, note, that I added an ID to your select tag so that you can more easily handle events to it (I called it myOptions).

Example: http://jsfiddle.net/S9WQv/

like image 169
JasCav Avatar answered Jan 03 '23 11:01

JasCav


As specified by JasCav using jQuery you can accomplish the same in javascript using

 <select onchange="alert(this.options[this.selectedIndex].text);">       <option value='option1'>Gateway 1</option>       <option value='option2'>Gateway 2</option>       <option value='option3'>Gateway 3</option>  </select> 

Alternatively, onclick event of option, but note that it is not compatible on all browsers.

<select>       <option value='option1' onclick="alert(this.value);" >Gateway 1</option>       <option value='option2'>Gateway 2</option>       <option value='option3'>Gateway 3</option> </select> 
like image 45
niksvp Avatar answered Jan 03 '23 10:01

niksvp