Kartik Select2 AutoFocus

Can anyone tell me how I can set the focus on a Select2 when a modal dialog is loaded?

I’ve tried autofocus on the widget itself, it didn’t work.

In the Index page, I tried
$(’#modal’).on(‘shown.bs.modal’, function () {
$(‘body’).on(‘shown.bs.modal’, ‘#modal’, function () {
$(’#select2-projects-clientid-container:visible:enabled:first’, this).focus();

On the modal page I’ve tried …

I just can’t seem to figure out a way to make it have the focus once the modal has loaded. I don’t need it to drop down or anything, simply have the focus.

I’ve had this problem and had to build a workaround with JS which you might need to adapt a bit for your use, but here it is:

function focusFirstElement(parent=null,timeout=100) {
	setTimeout(function() {
		var focusClass = '.focus_first';
		if ($(focusClass).is(":hidden") && $(focusClass).hasClass("select2-hidden-accessible") && $(focusClass).parent().is(":hidden"))
			focusClass = '.focus_second';
		if (parent != null)
			focusClass = parent +' '+ focusClass;
		try {
			if ($(focusClass).hasClass("select2-hidden-accessible") && $(focusClass).is('[disabled]') == false) {
		} catch (e) {}
	}, timeout);

Just add the focus_first class to your select2 element and call that function upon modal opening.

Here I have an example of how I do this:

$(document).on('click', '.showModalButton', function() {
	$('#modal').modal('show').find('#modalContent').load( $(this).attr('value'), function() { 
		focusFirstElement('#modalContent', 400)

In my case, when an HTML element with the showModalButton class is clicked, it will open the modal and run the script to focus on the element.

1 Like