Developer Desk
Developer Desk

Reputation: 2344

how to get chosen option value on hover/mouseover event using jquery chosen plugin?

I am trying to get option value on hover/mouseover event when option is hovered using chosen plugin....

Fiddle : Demo Fiddle

Here is js code...

   $("#myselect").chosen();

   $('#myselect').next('.chosen-container').on('mouseenter', 'li.active-result', function(e) {
    alert($(this).text());
    alert($(this).val()); // how to get option value...?
   });

Upvotes: 2

Views: 3781

Answers (3)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

As this plugin created new elements for options and to read option value you need find option matching text and read its value:

$('#myselect').next('.chosen-container').on('mouseenter', 'li.active-result', function(e) {
    var currentText = $(this).text();
    alert($(this).text());
    alert($('#myselect option').filter(function () { return $(this).html() == currentText; }).val()); // how to get option value...?
 });

Demo

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82251

You need event delegation for binding the events to dynamically added DOM:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$("body").on('mouseenter','li.active-result',function(){
  alert($(this).data('option-array-index'));   
});

Working Demo

Upvotes: 1

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

USe delegate for that, because chosen plugin creates the .active-result class elements dynamically.

$("#myselect").chosen();

$(document).on("hover",".active-result",function(){
 alert($(this).text());   
});

Fiddle

Edit

$(document).on("hover",".active-result",function(){
    alert($("#myselect option").eq($(this).data("option-array-index")).val());

});

Updated fiddle

Upvotes: 6

Related Questions