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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With