[Solved] Select2 Dropdowns close immediately after opening - Wordpress install


#1

Hello!

I have a wordpress installation with select2 installed (wonkily, I’m still learning development) via a snippets plugin used to replicate negate the need to directly edit functions.php.

The code is like so:

function enqueue_select2_jquery() {
    wp_register_style( 'select2css', '//cdnjs.cloudflare.com/ajax/libs/select2/3.4.8/select2.css', false, '1.0', 'all' );
    wp_register_script( 'select2', '//cdnjs.cloudflare.com/ajax/libs/select2/3.4.8/select2.js', array( 'jquery' ), '1.0', true );
    wp_enqueue_style( 'select2css' );
    wp_enqueue_script( 'select2' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_select2_jquery' );

function select2jquery_inline() {
    ?>
<script type='text/javascript'>
		
jQuery(document).ready(function ($) {

 
        $( document.body ).on( "click", function() {
             $( 'select' ).select2();
			closeOnSelect: false
				dropdownParent: $('select')
          });
    
});
</script>
    <?php
 }



add_action( 'wp_head', 'select2jquery_inline' );

Clicking on any Select2 box, briefly opens the dropdown, but then it closes again immediately. This seems to only happen in Chrome.

I’ve tried deactivating all plugins, and switching to the default “2019” theme. Still no joy.
I’ve also tried this code directly in functions.php, but to no avail.

Any help would, of course be very much appreciated.

Cheers in advance!


#2

Quick update:

It looks like I wasn’t being explicit enough with my targeting. I changed

$( 'select' ).select2();

to

$( '#aSpecificID' ).select2();
$( '#AnotherSpecificID' ).select2();

And so on.