html에서 select2 id값을 설정

javascript에서 id값으로 html의 select2 값을 조회 및 변경

<!DOCTYPE html>
<html>
  <head>
    <title>Select2 Test</title>
    <!-- select2 css cdn -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.9/css/select2.min.css" rel="stylesheet" />
  </head>
  <body>
    <br />
    <div style="margin-left:10px;">
      <select class="form-control select2" id="search_type" name="search_type">
        <option value="all">ALL</option>
        <option value="sql">SQL</option>
        <option value="os">OS</option>
      </select>
    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <!-- select2 javascript cdn -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.9/js/select2.min.js"></script>
    <script>
    
      //Initialize Select2 Elements
      $('.select2').select2({
        theme: "bootstrap4",
        width: 'auto',
        dropdownAutoWidth: true
      })
      
      //select2 선택값 변경
      $('#search_type').val('OS');
      // 위 코드로 변경이 되지 않는 경우
      $('#search_type').val('OS').trigger('change');
       
    </script>
  </body>
</html>

to Top