Skip to content

How do I initialize by default value with select2 and trigger ajax request(select2:select)?

I want the first element of the selectbox to be selected by default when my page loads. It is selected but does not make ajax request. I want it to trigger the ‘select2: select’ event. Only the selected part in selectbox changes, it doesn’t execute the ajax request. I want it to work like ‘select2: select’ when I assign the first element. So when I select the first element, it should be triggered in the ajax request.

// the part where I select the first element by default. The part that doesn't work as I want
$('select[name=items]').prop('selectedIndex', 1).trigger('change.select2');

// For event being selected in selectboxt
$('select[name=items]').on('select2:select', function (e) {
        $.ajax({
                "url":'myendpoint',
                "headers": {
                        
                },
                "method": "GET",
                "success": function (data) {
                     
                 //my operations
              })

})

Answer

You can do using change event this will get trigger when you do trigger('change') or use .trigger("select2:select") to trigger select2:select event.

Demo Code :

$('select[name=items]').select2({
  width: "100px"
});
//other way using change event
$('select[name=items]').on('change', function(e) {
  console.log("i am inside chnge")
  //your ajax call

})
//using select:2
$('select[name=items]').on('select2:select', function(e) {
  console.log("i am inside seclet")
  //your ajax call

})
$('select[name=items]').prop('selectedIndex', 1).trigger('change').trigger("select2:select"); //trigger both
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

<select name="items">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>