Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke onclick event on select2

I am trying to bind onclick to select input element with select2 initialization.

I want to bind a handler when the drop-down is clicked or focused.

<select class="form-control" id="type" name="type" required="required">
    <option value="breakfast" <?= ($type == 'breakfast')? 'selected' : '';?>>Breakfast</option>
    <option value="snacks" <?= ($type == 'snacks')? 'selected' : '';?>>Snacks</option>
</select>

Here's the js part:

$('#type').select2({}).on("select2-selecting", function(e) {
    console.log('not working');
});

I also tried "select2-open/opening" but to no avail. How do I make the event binding work?

like image 258
Azima Avatar asked Jan 01 '23 20:01

Azima


1 Answers

In the version 3.5.1 you're using, you should use select2-selecting instead of select2:selecting like :

$('#type').select2({}).on("select2-selecting", function(e) {
    console.log('not working');
});

$('#type').select2({});

$('#type').on("select2-opening", function(e) {
  console.log('Opening');
});
$('#type').on("select2-selecting", function(e) {
  console.log('Selecting');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.1/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.1/select2.min.js"></script>
<select style="width:300px" id="type">
  <option value="CA">California</option>
  <option value="NV">Nevada</option>
  <option value="OR">Oregon</option>
  <option value="WA">Washington</option>
</select>
like image 136
Zakaria Acharki Avatar answered Jan 05 '23 17:01

Zakaria Acharki