I have a lot of admin pages where an input (often inside a custom field metabox) is using a select2 dropdown. On some pages, I’ll notice that when I click on the input, it doesn’t automatically focus the text input so that I can start typing, which is usually what I want. So this adds a javascript to the footer of admin pages that attempts to correct that.

<?php

/**
 * Admin - JS: autofocus select2 input
 *
 * Appends JS to the footer of admin pages. Forces select2 inputs to autofocus when clicked.
 */
	
namespace ff2G6Nm;

if (\current_user_can('manage_options')) {
	
	\add_action( 'admin_footer', '\ff2G6Nm\add_script_to_page' );

	function add_script_to_page() { 
?>

<script type="text/javascript">
	window.addEventListener('DOMContentLoaded', ()=>{
		if (window.jQuery) {
			jQuery(document).on('select2:open', () => {
				setTimeout(focusInputOfTheOpenSelect2,100);
			});
			function focusInputOfTheOpenSelect2(){
				let basicClass = '.select2-container';
				let opendClass = '.select2-container--open';
				let focusClass = '.select2-container--focus';
				let dropdClass = '.select2-search.select2-search--dropdown';
				let fieldClass = `${dropdClass} input.select2-search__field[type="search"]`;
				let field = document.querySelector(`${opendClass} ${fieldClass}`);
				if (field) {
					// console.log(field);
					field.focus();
				}
			}
		}
	});
</script>

<?php }
	
}

Leave a Reply

Your email address will not be published. Required fields are marked *