jQuery open select by button

前端 未结 7 1172
小蘑菇
小蘑菇 2021-01-11 15:33

How to open select dropdown by button?

$(\'button\').on(\'click\', function() {
   $(\'select\').trigger(\'click\');
});

My code: http://js

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-11 16:01

    I found a great solution here: https://stackoverflow.com/a/18284923/8472295

    In your case you can wrap the button in a label and apply the same solution.

    HTML

    
    
    

    JS

    $("label").mouseover(function(){
        var $this = $(this);
        var $input = $('#' + $(this).attr('for')); 
        if ($input.is("select") && !$('.lfClon').length) {
            var $clon = $input.clone();
            var getRules = function($ele){ return {
                position: 'absolute',
                left: $ele.offset().left,
                top: $ele.offset().top,
                width: $ele.outerWidth(),
                height: $ele.outerHeight(),
                opacity: 0,
                margin: 0,
                padding: 0
            };};
            var rules = getRules($this);
            $clon.css(rules);
            $clon.on("mousedown.lf", function(){
                $clon.css({
                    marginLeft: $input.offset().left - rules.left,
                    marginTop: $input.offset().top - rules.top,
                });
                $clon.on('change blur', function(){
                    $input.val($clon.val()).show();
                    $clon.remove();
                });
                $clon.off('.lf');
            });
            $clon.on("mouseout.lf", function(){
                $(this).remove();
            });
            $clon.prop({id:'',className:'lfClon'});
            $clon.appendTo('body');
        }
    });
    

    Demo: http://jsfiddle.net/Yh3Jf/24/

    The js creates a clone of the select element which updates the original.

    Tested and works for me, in my case I used it to hide the select field with css, then the button triggers a drop down where a selection can be made.

提交回复
热议问题