Search From Start of Label

By default, Advanced Select will return any item whose label contains the search query. This snippet will change the search algorithm to only return items whose label starts with the search query.

Instructions

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

Code

Filename: gpadvs-search-from-start-of-label.js

/**
 * Gravity Perks // Advanced Select // Search From Start of Label
 * https://gravitywiz.com/documentation/gravity-forms-advanced-select/
 *
 * By default, Advanced Select will return any item whose label contains the search query. This
 * snippet will change the search algorithm to only return items whose label starts with the
 * search query.
 *
 * 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 ) {
	settings.score = function(search) {
		if ( ! search ) {
			return function() {
				// Item has no search query, return all items
				return 1;
			};
		}
		search = search.toLowerCase();
		return function(item) {
			if ( item.text.toLowerCase().startsWith( search ) ) {
				// High score for items starting with search query
				return 1;
			}
			// Zero score for items not starting with search query
			return 0;
		};
	};
	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.