The N World
The N World

Reputation: 109

trigger('change') is not working on Select

I have created a select2 dropdown with

    <select class="form-control select2"  id="country">
<option value="1">India</option>
<option value="2">Aus</option>
<option value="3">usa</option>
    </select>

Now i am selecting selected value via jquery trigger event

$('#country').val('1').trigger('change'); 

here, country gets selected with passed value but On this event i also want to trigger change event which is not triggering.

$("#country").change(function() {
alert('on country change');
});

If i change manually from select2 then the change event fires and it shows the alert but i want to fire the change event automatically when the country value changes from jquery. Any clues?

Thanks in advance.

Upvotes: 0

Views: 13682

Answers (1)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14198

You should trigger after change function, like this

$("#country").change(function() {
  alert('on country change');
});

$('#country').val('1').trigger('change');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet"/>



<select class="form-control select2"  id="country" style="width: 100px;">
    <option value="1">India</option>
    <option value="2">Aus</option>
    <option value="3">usa</option>
  </select>

Upvotes: 2

Related Questions