--- title: Add, select, or clear items metadata: description: Programmatically adding, selecting, and clearing options in a Select2 control. taxonomy: category: docs --- ## Creating new options in the dropdown New options can be added to a Select2 control programmatically by creating a new [Javascript `Option` object](https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement/Option) 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'); ``` The third parameter of `new Option(...)` determines whether the item is "default selected"; i.e. it sets the `selected` attribute for the new option. The fourth parameter sets the options actual selected state - if set to `true`, the new option will be selected by default. ### Create if not exists You can use `.find` to select the option if it already exists, and create it otherwise: ``` // Set the value, creating a new option if necessary if ($('#mySelect2').find("option[value='" + data.id + "']").length) { $('#mySelect2').val(data.id).trigger('change'); } else { // Create a DOM Option and pre-select by default var newOption = new Option(data.text, data.id, true, true); // Append it to the select $('#mySelect2').append(newOption).trigger('change'); } ``` ## Selecting options To programmatically select an option/item for a Select2 control, use the jQuery `.val()` method: ``` $('#mySelect2').val('1'); // Select the option with a value of '1' $('#mySelect2').trigger('change'); // Notify any JS components that the value changed ``` You can also pass an array to `val` make multiple selections: ``` $('#mySelect2').val(['1', '2']); $('#mySelect2').trigger('change'); // Notify any JS components that the value changed ``` Select2 will listen for the `change` event on the `