How to Reset Select2 and Multiselect Fields of the Form

0

I have a registration form where I reset the fields when entering a record with the following:

document.getElementById(id).reset(); //Aqui passo o id do formulário

The problem is that I now have a select2 multiselect that are not being reset.

<select name="funcao_id" class="form-control select2">
    ...
        <option>...</option>
    ...
</select>

<select multiple id="exames" name="exames[]" class="form-control">
    ...
        <option>...</option>
    ...
</select>

<script>
    $(function () { $(".select2").select2(); });
</script>
  

I put only the relevant parts of the code, if need be I put something else.

    
asked by anonymous 06.10.2016 / 22:47

2 answers

2

The syntax for resetting select2 is .select2("val", ""); .

You can use this:

$('select').select2(); // iniciar o select2
$('form').on('reset', () => { // acionar quando o reset acontecer
  $(this).find('select').select2("val", ""); // fazer reset do select2
});

jsFiddle: link

    
06.10.2016 / 23:01
0

try this:

$('#multiselect').prop('selectedIndex',0);
$('#select2').prop('selectedIndex',0);

This code will leave the first item selected

    
06.10.2016 / 23:05