Click on Option Event

Click on option event

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/

Javascript run function on option click

<select> elements support the onchange event.

http://w3schools.com/jsref/event_onchange.asp

Bind click event on select option

In my case following code works

$('#myItem').change(function(){
//do somthing
})

adding onclick event to html select option

Try it in the onchange handler:

function checkAlert(evt) {  if (evt.target.value === "Say Hello") {    alert('Hello');  }}
<select onchange="checkAlert(event)">  <option>Test</option>  <option>Say Hello</option></select>

How to trigger click event on select element? (not change)

"click selection box->drop menu->click selected option->trigger event"

First of all do not use alert(), it prompts for an extra click you really don't need to waste your time on. Use console.log().

The following demo:

  • Delegates the click event to select#x:

$('#x').on('click',...

  • Once clicked, it will trigger a focus event on every even click:

if (cnt % 2 === 0) { $(this).trigger('focus');}

  • select#x is also delegated to the focus event and will call optionTrigger():

$('#x').on('focus', optionTrigger);

  • function optionTrigger() will log the selected <option> index and text:

if (cnt < 2) {...

...$(this).trigger('blur'); }

var idx = $(this)[0].selectedIndex;

var txt = $(this).find('option').eq(idx).text();


Demo

var cnt = 1;

$("#x").on("click", function(e) {
if (cnt % 2 === 0) {
$(this).trigger('focus');
}
cnt++;
});

$('#x').on('focus', optionTrigger);

function optionTrigger(e) {
if (cnt < 2) {
$(this).trigger('blur');
} else {
var idx = $(this)[0].selectedIndex;
var txt = $(this).find('option').eq(idx).text();
console.log(idx + ': ' + txt);
}
}
<select id="x">
<option>A</option>
<option>B</option>
<option>C</option>
</select>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


Related Topics



Leave a reply



Submit