11

I want to alert an option when the mouse-cursor is over it. I use this code:

$("select > option").hover(function ()
    { 
        alert($(this).attr("id"));
    });

Unfortunately, this is neither working in IE nor in FF.

Can someone give me a hint please?

gdoron
  • 147,333
  • 58
  • 291
  • 367
enne87
  • 2,221
  • 8
  • 32
  • 61
  • 1
    check the below links , useful info http://stackoverflow.com/questions/2064011/select-option-hover-is-not-working-in-ie – kobe Feb 04 '12 at 19:48
  • one more http://stackoverflow.com/questions/4599975/html-select-box-options-on-hover – kobe Feb 04 '12 at 19:49

3 Answers3

21

You can try this.

$("select").hover(function (e)
{
     var $target = $(e.target); 
     if($target.is('option')){
         alert($target.attr("id"));//Will alert id if it has id attribute
         alert($target.text());//Will alert the text of the option
         alert($target.val());//Will alert the value of the option
     }
});
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • 2
    The reason being that Chrome and IE won't let you capture events directly on option elements, but do allow you to capture events on select elements. – Willem Mulder Feb 04 '12 at 20:58
  • I'm struggling with this for IE 8; I'm just not seeing mouseover or hoever events from the options, just the select. Seems to work in Chrome and FF, but not in IE. jQuery("#" + id).closest(".t-palette").find("select").hover(function (event) { T5.console.debug("hover " + this.id); var $target = jQuery(event.target); if ($target.is("option")) { T5.console.debug("option = " + $target.text()); this.title = $target.text(); } }); – Howard M. Lewis Ship Jul 10 '12 at 22:41
  • 14
    Its not working for me .. i am trying ths same code. when i hover over on options it does't alert. . – Tarun Gupta Sep 13 '13 at 01:25
5

If you make a "listbox" type select box by adding a "size=x" attribute like this:

<select size="3">
   <option>...</option>
   <option>...</option>
</select>

The hover event will work on the option elements:

$('option').hover(function(){
     //code here
});
A_funs
  • 1,228
  • 2
  • 19
  • 31
1

Here's a workaround (quite decent I guess)-

  • Use mouseover event to set the size of the select box equal to the no. of its children
  • Use mouseenter event to get the options. mouseenter works on options perfectly when size attribute is there (we all know that now)
  • Use mouseout event to set the size of the select box back to 1, to get our normal select box back :)

JSFiddle

Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90