The question at hand involves creating a select box where the option descriptions are visible when the field is hovered over, rather than clicking to open the options.
To achieve this functionality, we utilized a JavaScript approach as follows:
$('#selectUl li:not(":first")').addClass('unselected'); // Hide the 'unselected' elements in the ul. $('#selectUl').hover( function(){ // mouse-over $(this).find('li').click( function(){ $('.unselected').removeClass('unselected'); // removes the 'unselected' style $(this).siblings('li').addClass('unselected'); // adds 'unselected' style to all other li elements var index = $(this).index(); $('select option:selected').removeAttr('selected'); // deselects the previously-chosen option in the select $('select[name=size]') .find('option:eq(' + index + ')') .attr('selected',true); // assumes a 1:1 relationship between the li and option elements }); }, function(){ // mouseout (or mouseleave, if they're different, I can't remember). });
In this approach, the unselected class is utilized to initially hide all options except the first one. When the ul is hovered over, the non-clicked elements are given the unselected class, effectively disappearing. The selected element remains visible and its corresponding value is reflected in the underlying select field.
The above is the detailed content of How to Create Hoverable Select Box Options with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!