Resetting Select2 value in dropdown with reset button

前端 未结 16 1077
别跟我提以往
别跟我提以往 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:45

    I see three issues:

    1. The display of the Select2 control is not refreshed when its value is changed due to a form reset.
    2. The "All" option does not have a value attribute.
    3. The "All" option is disabled.

    First, I recommend that you use the setTimeout function to ensure that code is executed after the form reset is complete.

    You could execute code when the button is clicked:

    $('#searchclear').click(function() {
        setTimeout(function() {
            // Code goes here.
        }, 0);
    });
    

    Or when the form is reset:

    $('form').on('reset', function() {
        setTimeout(function() {
            // Code goes here.
        }, 0);
    });
    

    As for what code to use:

    Since the "All" option is disabled, the form reset does not make it the selected value. Therefore, you must explicitly set it to be the selected value. The way to do that is with the Select2 "val" function. And since the "All" option does not have a value attribute, its value is the same as its text, which is "All". Therefore, you should use the code given by thtsigma in the selected answer:

    $("#d").select2('val', 'All');
    

    If the attribute value="" were to be added to the "All" option, then you could use the code given by Daniel Dener:

    $("#d").select2('val', '');
    

    If the "All" option was not disabled, then you would just have to force the Select2 to refresh, in which case you could use:

    $('#d').change();
    

    Note: The following code by Lenart is a way to clear the selection, but it does not cause the "All" option to be selected:

    $('#d').select2('data', null)
    

提交回复
热议问题