Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
[JavaScript] Using jQuery To Set Select2 Selected Value
* ht to @GaryJones for some refactoring
// Lookup and store the select element to reference it throughout the code
var option, $select = jQuery( '#s2id_select2_element' );
/* Attempt to find the option element that belongs to the select element
* identified by the above ID based on the current window's location.
* Grab [0] so that we get the actual element rather than a jQuery-wrapped
* object.
option = $select.find( 'option[value="' + window.location.href + '"]' )[0];
/* Check to see if the option for this URL exists. If so, then set the
* select2's option value equal to that of the current page; otherwise,
* nothing happens and the default value continues to display.
if ( 'undefined' !== typeof option ) {
$select.select2( 'val', window.location.href );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment