skip to Main Content

How to write on open event for select box using select2 in jquery. I tried using .on("change"), but it gets fired once we click the option inside the selectbox. I need the event which will get triggered the moment I open the selectbox

I tried with .click, .change, .focus

   

 $('#js_pdp_campus').on('select2:open', function(e) {
            
            console.log("hi");
            let $campusData = "/product-commons/getcampusdata/?baseProductCode=MBS_86530";
            $.ajax({
                type: 'GET',
                url: $campusData,
                contentType: 'application/json',
                success: function (data) {
                    console.log("poc data is", data);
                },
                error: function(error) {
                }
            });
            return $campusData;
        })
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<script src="//code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>

<div class="control">
  <select name="campus" id="js_pdp_campus" class="campusDataClass js-pdp-course-finder-select bned-select-input js-enable-select-input form-control js-basic-single" role="listbox">
    <option>campus 1</option>
    <option>campus 2</option>
    <option>campus 3</option>
  </select>
</div>

2

Answers


  1. You can use events https://select2.org/programmatic-control/events

    $(document).ready(function() {
      $('.js-example-basic-single').select2();
      $('.js-example-basic-single').on('select2:opening', function(e) {
        console.log("select2:opening");
      });
    });
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
    <select class="js-example-basic-single" name="state">
      <option value="AL">Alabama</option>
      <option value="WY">Wyoming</option>
    </select>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
    Login or Signup to reply.
  2. Use .focus() method for this. Try something like below.

    $('.sbox').focus(function() {
      console.log("WORKING..");
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <input>
    <select class="sbox">
      <option>option 1</option>
      <option>option 2</option>
      <option>option 3</option>
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search