Auto Select on Match

Automatically select the matching option based on the search value.

Instructions

  1. Install this snippet with our free Custom JavaScript plugin. https://gravitywiz.com/gravity-forms-code-chest/

Code

Filename: gpadvs-auto-select-on-match.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
 * Gravity Perks // Advanced Select // Auto Select on Match
 * https://gravitywiz.com/documentation/gravity-forms-advanced-select/
 *
 * Automatically select the matching option based on the search value.
 *
 * Instructions:
 *
 * 1. Install this snippet with our free Custom JavaScript plugin.
 *    https://gravitywiz.com/gravity-forms-code-chest/
 */
gform.addFilter( 'gpadvs_settings', function( settings, gpadvs, selectNamespace ) {
	if ( gpadvs.formId == GFFORMID ) {
		let lastQuery = '';
		settings.onType = function( str ) {
			lastQuery = str;
			const tomSelect = window[ selectNamespace ];
			const matchedKey = Object.keys( tomSelect.options ).filter( function( key ) {
				return -1 !== tomSelect.options[ key ].text.toLowerCase().indexOf( str.toLowerCase() );
			} );

			if ( 1 === matchedKey.length ) {
				tomSelect.setValue( tomSelect.options[ matchedKey[0] ].id, false );
				// Especially after an option was previously selected, if the first
				// character typed next to resume search matches just one option,
				// the dropdown would remain open; blur closes it immediately.
				tomSelect.blur();
			}
		};

		const originalOnLoad = settings.onLoad;
		settings.onLoad = function() {
			if ( originalOnLoad ) originalOnLoad.call( this );
			settings.onType( lastQuery );
		};
	}

	return settings;
} );

Leave a Reply

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

  • Trouble installing this snippet? See our troubleshooting tips.
  • Need to include code? Create a gist and link to it in your comment.
  • Reporting a bug? Provide a URL where this issue can be recreated.

By commenting, I understand that I may receive emails related to Gravity Wiz and can unsubscribe at any time.