javascript - How to change the value of select2 without trigger event? - Stack Overflow

I have a select2select element whose value I am setting through jQuery$("#select2").val(elmen

I have a select2select element whose value I am setting through jQuery

$("#select2").val(elment_id).trigger('change');

However, I have already defined an onchange event handler.

$('#select2').on('change', function(e) {
//TODO
});

I would like to just change(set) the value of select2 without triggering a change event. Any idea, how to do it?

I have a select2select element whose value I am setting through jQuery

$("#select2").val(elment_id).trigger('change');

However, I have already defined an onchange event handler.

$('#select2').on('change', function(e) {
//TODO
});

I would like to just change(set) the value of select2 without triggering a change event. Any idea, how to do it?

Share Improve this question edited Apr 29, 2019 at 6:50 Shinjo 6936 silver badges23 bronze badges asked Apr 29, 2019 at 6:14 KiranKiran 8,54838 gold badges117 silver badges181 bronze badges 2
  • Why do yo call trigger('change') to change the value? Isn't just $("#select2").val(elment_id) enough? – sassy_rog Commented Apr 29, 2019 at 6:18
  • This doesnt change the value on the select2 element. – Kiran Commented Apr 29, 2019 at 6:22
Add a ment  | 

3 Answers 3

Reset to default 10

There is a special event to refresh it:

$("#select2").val(elment_id).trigger('change.select2');

From docs:

It's mon for other ponents to be listening to the change event, or for custom event handlers to be attached that may have side effects. To limit the scope to only notify Select2 of the change, use the .select2 event namespace:

$('#mySelect2').val('US'); // Change the value or make some change to the internal state
$('#mySelect2').trigger('change.select2'); // Notify only Select2 of changes

You could do with Jquery extension create new prototype like this

$.fn.extend({
  Val: function(a) {
    $(this).val(a).trigger('change');
  }
})

$('#select2').Val(1)

It depends when you want to change the value in select element. It depends from other element? If you want to fire event on select element change, but don't want to trigger already defined 'onchange' action, you can give your select next unique class, and build next 'onchange' event for that class. But, as i said previously, i don't know what you want to achieve, and it's hard to say which solution will be the best

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743751090a4500911.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信