Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear select2 without triggering change event

I have a select2 input that I'm using and on 'change' I'm grabbing the values and performing an action. I'm trying to clear that select2 without triggering a change event. Is this possible?

To clear the select2 I'm using the following code:

$docInput.select2('data', null);

This clears the input as desired, but also triggers a change event which runs through my other code. There must be a way to silence the trigger. Any ideas?

like image 864
Ryan Gill Avatar asked Jul 23 '13 19:07

Ryan Gill


People also ask

How do I delete select 2 selection?

In order to clear the selection of those values which are selected using a Select2 drop down,we can use the empty() function. The dropdown can be reset using Jquery. $(“#select2_example”). empty();

What does trigger (' Change ') do?

jQuery change() Method The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected.

How do I update Select2 options?

How do I update Select2 options? New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).

What is the use of Select2 in jquery?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.


2 Answers

You can use the following with Select2 4.x

$docInput.val(null).trigger('change.select2');
like image 162
Oleksii Polivanyi Avatar answered Nov 09 '22 19:11

Oleksii Polivanyi


I believe all you need is:

$docInput.select2('data', null, false);

like image 16
Mike Fielden Avatar answered Nov 09 '22 19:11

Mike Fielden