--- title: Methods taxonomy: category: docs process: twig: true never_cache_twig: true --- Select2 supports methods that allow programmatic control of the component. ## Programmatically adding options 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.name, 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.name, data.id, true, true); // Append it to the select $('#mySelect2').append(newOption).trigger('change'); } ``` ## Selecting an option To programmatically select an option/value for a Select2 control, use the jQuery `.val()` method: ``` $('#mySelect2').val('US'); // Select the option with a value of 'US' $('#mySelect2').trigger('change'); // Notify any JS components that the value changed ``` Select2 will listen for the `change` event on the `