Home  >  Article  >  Web Front-end  >  How to Display Select Box Options on Hover Instead of Clicking?

How to Display Select Box Options on Hover Instead of Clicking?

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 06:08:02777browse

How to Display Select Box Options on Hover Instead of Clicking?

Hovering to Display Select Box Options

The issue presented involves creating a select box that displays options on hover instead of after clicking. The code provided is a simple select box:

<select name="size">
   <option value="small">Small</option>
    <option value="medium">Medium</option>
    <option value="large">Large</option>
</select> 

Solution

The provided jQuery solution aims to achieve the desired behavior:

$('#selectUl li:not(":first")').addClass('unselected');
$('#selectUl').hover(
    function(){
    $(this).find('li').click(
        function(){
            $('.unselected').removeClass('unselected');
            $(this).siblings('li').addClass('unselected');
            var index = $(this).index();
            $('select option:selected').removeAttr('selected');
            $('select[name=size]')
                .find('option:eq(' + index + ')')
                .attr('selected',true);
        });
    },
    function(){
});

Explanation

  • The code initially hides all options except the first one by adding the "unselected" class.
  • Upon hovering over the ul, it enables clicking on the options to change the selection.
  • Clicking an option removes the "unselected" class from all others and adds it to the clicked option, ensuring it remains visible.
  • The selected option's index is used to update the select element, making the change persistent.

Additional Features

The solution has been extended to include:

  • An alert to demonstrate the updated select element's value.
  • Styling to improve the visibility of the selected and hovered options.
  • A plug-in approach for easier implementation in other projects.
  • A guidance text element to explain the purpose of the select box.

The above is the detailed content of How to Display Select Box Options on Hover Instead of Clicking?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn