0

how to set value to select2?, I read in this SO, there are many ways, but nothing works for me, anybody can help?

<div class="form-group">
     <label class="col-form-label" for="input-user_type">User type</label>
     <select class="form-control select2-single" id="user_type" name="user_type">
         <option></option>
         <option>Internal</option>
         <option>External</option>
         <option>Admin</option>
     </select>

     <script type="text/javacsript">
       $("#user_type").val("2");   **--> have tried this and no luck**
       $("#user_type").select2().trigger('change'); **--> have tried this and no luck**
       $('#user_type').val("2").select2();**--> have tried this and no luck**
       $("#user_type").select2().select2('val','2'); **--> have tried this and no luck**
     </script>
  </div>
FBDon
  • 23
  • 6
  • None of your options has "value == 2" so `.val(2)` won't be able to select the option with value 2, because there isn't one. – freedomn-m Apr 04 '22 at 15:54
  • Your setup the dropdown as a select 2 with `$("#user_type").select2()` then *separately* you can set the value using `$("#user_type").val("Admin").change()` (or .trigger("change")). Example: https://jsfiddle.net/2gswLhra/ – freedomn-m Apr 04 '22 at 15:57
  • You have a typo: ` – T.Trassoudaine Apr 04 '22 at 16:01

0 Answers0