jQuery click event not firing on optgroup

后端 未结 5 571
不思量自难忘°
不思量自难忘° 2021-01-13 23:10

I have the following code - example on jsFiddle


                        
    
提交评论

  • 2021-01-13 23:33

    Here's how you can solve it using jQuery.

    First assign the event to the optgroup, and see if propagation was stopped.

    $('optgroup').on('click',function(e) {
        if(!e.isPropagationStopped()){
            if ($(this).find('option:visible').length == $(this).children().length) {
                $(this).children().hide();
            }
            else {
                $(this).children().show();
            }
        }
    });
    

    Next up, we want to prevent the previous piece of code to trigger when we click one of the child options.

    $('optgroup > option').on('click',function(e) {
        e.stopPropagation();
        $(this).parent().trigger('change');
    });
    

    The "trigger" event that is called at the end of the function is to ensure that any other assigned triggers on the change event are still triggered.

    0 讨论(0)
  • 2021-01-13 23:38

    There is one sophisticated solution that allows you to listen click events on optgroups in multiple select. The idea is listen clicks at the parent select item and calculate if user has clicked at the optgroup title.

    $('#multipleSelectId').click(function(event) {
        var y = event.pageY - $(this).offset().top;
        var row = Math.floor((y - 4) / 15);
        $(this).find('optgroup').each(function() {
            if (row == 0) {
                onOptgroupClick($(this));       
                return false;
            }
            row -= $(this).children().length + 1; 
        });
    });
    

    This approach has been tested in Chromium 30, Firefox 25, IE 9.

    I don't know whether it can be applied to single selects, but with "multiple=multiple" it works like a charm.

    0 讨论(0)
  • 2021-01-13 23:38

    So the short answer on this seems to be that this is not possible. It is not possible to take a normal select with optionGroups and turn it into an accordion styled select list where initially, only the optiongroup items are displayed and clicking an optiongroup item expands its children (the options).

    It seems that no browsers truly support clicking a group item in the select list. While there is an onClick event, the event acts more like you've clicked the selected item.

    0 讨论(0)
  • 2021-01-13 23:54
    $(document).ready(function() {
        $("select").change(function() {
            var clicked = $(this)
                             .find('option:selected') // get selected option
                             .parent()   // get that option's optgroup
                             .attr("label");   // get optgroup's label
    
            alert( clicked );
        });
    });
    

    DEMO

    Note

    .click() is wrong event you're using. see comment

    0 讨论(0)
  • 提交回复
    热议问题