jQuery open select by button

前端 未结 7 1113
小蘑菇
小蘑菇 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 think you should have a look at this page:

    Can I open a dropdownlist using jQuery

    It seems like it is not possible to do this directly, but tools exists to emulate what you are trying to do.

    An easy solution would be to use the "chosen"-plugin for jquery: http://harvesthq.github.io/chosen/

    This also gives you some great advantages over normal selects, and its easy to use.

    On this you can simply fire a "mousedown" event like the following:

    $('#dropdown_id_chzn').trigger('mousedown')
    

    Given you have chosen (and jquery) enabled on your page the following code should do the trick:

    HTML:

    
    

    JavaScript:

    $('select[name="foo"]').chosen();
    $('#foo_chzn').trigger('mousedown');
    

    Notice that chosen automatically appends the "_chzn" to your dropdown-name, which is what you should use in your selector

提交回复
热议问题