How do I reset a jquery-chosen select option with jQuery?

前端 未结 21 728
一个人的身影
一个人的身影 2020-11-30 21:42

I have tried numerous things and nothing seems to be working.

I am using jQuery and Chosen plugin.

Methods I have tried:

var select = jQuery(         


        
21条回答
  •  温柔的废话
    2020-11-30 22:30

    Setting the select element's value to an empty string is the correct way to do it. However, that only updates the root select element. The custom chosen element has no idea that the root select has been updated.

    In order to notify chosen that the select has been modified, you have to trigger chosen:updated:

    $('#autoship_option').val('').trigger('chosen:updated');
    

    or, if you're not sure that the first option is an empty string, use this:

    $('#autoship_option')
        .find('option:first-child').prop('selected', true)
        .end().trigger('chosen:updated');
    

    Read the documentation here (find the section titled Updating Chosen Dynamically).


    P.S. Older versions of Chosen use a slightly different event:

    $('#autoship_option').val('').trigger('liszt:updated');
    

提交回复
热议问题