最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - trigger('change') is not working on Select - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share edited Mar 4, 2022 at 7:43 Nguyễn Văn Phong 14.2k19 gold badges46 silver badges63 bronze badges asked Jan 7, 2020 at 1:36 The N WorldThe N World 1091 gold badge1 silver badge7 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 2

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./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/select2/4.0.10/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare./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>

发布评论

评论列表(0)

  1. 暂无评论