-
-
Save tommcfarlin/c30ff7f088f26d4e5761 to your computer and use it in GitHub Desktop.
[JavaScript] Using jQuery To Set Select2 Selected Value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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