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.
JavaScript
x
19
19
1
// the part where I select the first element by default. The part that doesn't work as I want
2
$('select[name=items]').prop('selectedIndex', 1).trigger('change.select2');
3
4
// For event being selected in selectboxt
5
$('select[name=items]').on('select2:select', function (e) {
6
$.ajax({
7
"url":'myendpoint',
8
"headers": {
9
10
},
11
"method": "GET",
12
"success": function (data) {
13
14
//my operations
15
})
16
17
})
18
19
Advertisement
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 :
JavaScript
1
16
16
1
$('select[name=items]').select2({
2
width: "100px"
3
});
4
//other way using change event
5
$('select[name=items]').on('change', function(e) {
6
console.log("i am inside chnge")
7
//your ajax call
8
9
})
10
//using select:2
11
$('select[name=items]').on('select2:select', function(e) {
12
console.log("i am inside seclet")
13
//your ajax call
14
15
})
16
$('select[name=items]').prop('selectedIndex', 1).trigger('change').trigger("select2:select"); //trigger both
JavaScript
1
10
10
1
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css">
2
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
3
4
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
5
6
<select name="items">
7
<option>1</option>
8
<option>2</option>
9
<option>3</option>
10
</select>