All,
I have two select boxes :
Depending on what option is selected in Fruit will affect the options of FruitQuantity.
So using select2, I wanted to replace all the options in a select simply by doing this.
var options = [];
$.each(pageData.products[selectedFruit].quantities, function (key, value) {
options.push({
text: value.quantity,
id: value.quantity,
})
});
console.log(options.length);
$quantitySelect.select2( { data : options });
The problem is that select2 is just appending the new data on to what exists already. I want it to clean out all the options and add the new ones.
Otherwise my select box is filling up with incorrect options.
I tried this from this question Clear dropdown using jQuery Select2
$quantitySelect.select2('data', null)
This does nothing though, it doesn't clear it.
Help me Obi Wan, you're my only hope.
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).trigger('change');
Disabling a Select2 controlSelect2 will respond to the disabled attribute on <select> elements. You can also initialize Select2 with disabled: true to get the same effect.
Your best option is to use the placeholder support in Select2 and include a blank option tag as your default selection.
Select2 does not function properly when I use it inside a Bootstrap modal. This issue occurs because Bootstrap modals tend to steal focus from other elements outside of the modal. Since by default, Select2 attaches the dropdown menu to the <body> element, it is considered "outside of the modal".
Assuming you work with select2 4.0.0, and the following kind of HTML:
<select id="fruits">
<option value="apple" selected>Apples</option>
<option value="pear">Pears</option>
</select>
<select id="quantities"></select>
You'll need to listen to the "change"
event on the "#fruits"
control, and each time it changes, you-'ll need to re-populate your "#quantities"
dropdown with relevant data.
Here's how it will look like:
var initQuantitiesDropdown = function () {
var options = [];
var selectedFruit = $("#fruits").val();
$.each(pageData.products[selectedFruit].quantities, function (key, value) {
options.push({
text: value,
id: key
});
})
$("#quantities").empty().select2({
data: options
});
};
$("#fruits").select2().change(initQuantitiesDropdown);
initQuantitiesDropdown();
You can see this in action in this JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With