How to Reset Form Select2 and Multiselect Fields

Asked

Viewed 1,511 times

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 I have a field now Select2 and a 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, in case I need something else.

2 answers

2


The syntax to reset the Select2 is .select2("val", "");.

You can use it like this:

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

jsFiddle: http://jsfiddle.net/a7gx0yyd/

0

try like this:

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

this code will leave selected the first item

Browser other questions tagged

You are not signed in. Login or sign up in order to post.