Reputation: 1636
I'd like to be able to reset (ie empty values and setting placeholder like on a "fresh" one) a Select2 dropdown. To be more precise, I have dependant dropdowns and clearing one should clear the depending ones.
As an example, I could have country, region and city: clearing country should clear region and city.
I tried several things but never was able to programmatically trigger the clear. The most obvious one was $('#my-select').empty()
but the placeholder is not re-set and the selected value remains (even if it is not displayed).
Using $('#my-select').select2('data', {})
(or $('#my-select').select2('data', null)
) is not yielding the desired result and getting the error:
Error: Option 'data' is not allowed for Select2 when attached to a element.
Is there an efficient solution for that?
Upvotes: 1
Views: 10481
Reputation: 2047
In Select2 v3.4.1, I removed the Li elements from UL but only the "select2-search-choice" tags:
$('.select2-search-choice').remove();
Upvotes: 1
Reputation: 1636
Well...
It a way, it is working on a minimal example (see below). On this example, the second select does not recover it's placeholder on reset (let's say it is almost working). It means the legacy code I'm working on has an issue somewhere (given the error, I guess the JSP tag generates a <select>
).
The issue does not seem to be where I was looking for.
So here is the solution (but not the solution to my real issue).
<!DOCTYPE html>
<html lang="en">
<head>
<title>Select2 example</title>
<link href="select2-release-3.2/select2.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
<fieldset>
<legend>Example</legend>
<label for="first-select">First</label>
<input id="first-select" />
<label for="second-select">Second (depends on first)</label>
<input id="second-select" />
</fieldset>
<script src="jquery-1.9.1.min.js"></script>
<script src="select2-release-3.2/select2.js"></script>
<script type="text/javascript">
$(function() {
var secondData = [{id:0,text:'1'},{id:1,text:'2'},{id:2,text:'3'},{id:3,text:'4'}];
$(document).ready(function() {
// Init first dropdown.
$('#first-select').select2({
allowClear: true,
placeholder: 'Select a value',
data: [{id:0,text:'A'},{id:1,text:'B'},{id:2,text:'C'},{id:3,text:'D'},{id:4,text:'E'}]
});
// Init second dropdown.
$('#second-select').select2({
allowClear: true,
placeholder: 'Select a value',
data: {}
});
});
$(document).on('change', '#first-select', function() {
if ($(this).val() == "") {
// Clear second
$('#second-select').select2({
allowClear: true,
placeholder: 'Select a value',
data: {}
});
} else {
// Fill second
$('#second-select').select2({data: secondData});
}
});
});
</script>
</body>
</html>
Upvotes: 1