Append new element programmatically with select2
To append a new element programmatically with Select2, you can use the appendNewOption
method. Here's an example:
$('#mySelect2').select2().appendNewOption({
id: 5,
text: 'New Option'
});
In this example, #mySelect2
is the ID of the Select2 element, and id
and text
are the properties of the new option.
If you want to append an option with a custom HTML content, you can use the appendNewOption
method with an object that contains the text
and html
properties:
$('#mySelect2').select2().appendNewOption({
text: 'New Option',
html: '<span style="color: red;">New Option</span>'
});
In this example, the new option will have the text "New Option" and the HTML content <span style="color: red;">New Option</span>
.
You can also use the appendNewOption
method to append an option with a custom data attribute:
$('#mySelect2').select2().appendNewOption({
id: 5,
text: 'New Option',
data: {
foo: 'bar'
}
});
In this example, the new option will have the foo
attribute set to bar
.
Note that the appendNewOption
method is only available in Select2 4.0 and later versions. In earlier versions, you can use the data.add
method to append a new option:
$('#mySelect2').select2('data', function(data) {
data.push({
id: 5,
text: 'New Option'
});
return data;
});
In this example, the data
method is used to get the current data of the Select2 element, and then the push
method is used to add a new option to the data array.