Resetting Select2 value in dropdown with reset button

前端 未结 16 1158
别跟我提以往
别跟我提以往 2020-12-23 13:00

What would be the best way to reset the selected item to default? I\'m using Select2 library and when using a normal button type=\"reset\", the value i

16条回答
  •  孤独总比滥情好
    2020-12-23 13:50

    What I found works well is as follows:

    if you have a placeholder option like 'All' or '-Select-' and its the first option and that's that you want to set the value to when you 'reset' you can use

    $('#id').select2('val',0);
    

    0 is essentially the option that you want to set it to on reset. If you want to set it to the last option then get the length of options and set it that length - 1. Basically use the index of whatever option you want to set the select2 value to on reset.

    If you don't have a placeholder and just want no text to appear in the field use:

    $('#id').select2('val','');
    

提交回复
热议问题