Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active July 12, 2016 09:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tommcfarlin/c30ff7f088f26d4e5761 to your computer and use it in GitHub Desktop.
Save tommcfarlin/c30ff7f088f26d4e5761 to your computer and use it in GitHub Desktop.
[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